感谢这篇精彩的文章。在“堆存储”部分中,我注意到 main 函数检查了 /* malloc 失败 */,但是由于我们正在相同的函数 (get_heap_array) 中初始化 *heap_nums 以尝试分配内存,因此我们需要在尝试访问数组之前添加验证,以避免在分配失败时出现段错误 (SIGSEGV)。
int *get_heap_array(unsigned n) {int *heap_nums = malloc(sizeof(int) * n);
/* 检查堆分配 */if (NULL == heap_nums) /* 失败? */return NULL; /* 如果是,则返回 NULL */
unsigned i;for (i = 0; i < n; i++)heap_nums[i] = i + 1; /* 初始化数组 */
/* 变量 heap_nums 和 i 的堆栈存储空间在 get_num_array 返回时自动释放 */automatically when get_num_array returns */return heap_nums; /* 返回 (指针的副本) */ }
我希望从你那里学到更多!
撰写的评论
感谢这篇精彩的文章。在“堆存储”部分中,我注意到 main 函数检查了 /* malloc 失败 */,但是由于我们正在相同的函数 (get_heap_array) 中初始化 *heap_nums 以尝试分配内存,因此我们需要在尝试访问数组之前添加验证,以避免在分配失败时出现段错误 (SIGSEGV)。
int *get_heap_array(unsigned n) {
int *heap_nums = malloc(sizeof(int) * n);
/* 检查堆分配 */
if (NULL == heap_nums) /* 失败? */
return NULL; /* 如果是,则返回 NULL */
unsigned i;
for (i = 0; i < n; i++)
heap_nums[i] = i + 1; /* 初始化数组 */
/* 变量 heap_nums 和 i 的堆栈存储空间在 get_num_array 返回时自动释放 */
automatically when get_num_array returns */
return heap_nums; /* 返回 (指针的副本) */
}
我希望从你那里学到更多!