【发布时间】:2014-08-13 22:57:35
【问题描述】:
在下面代码的末尾,我需要将哪个指针插入 free()、array 或 temp_array?哪一个或哪一个会释放内存块有关系吗?
int *array = 0;
int *temp_array = 0;
int count = 0;
array = malloc(sizeof(int));
// skipping code where count is calculated...
temp_array = realloc(array, count * sizeof(int));
if (temp_array == NULL) {
free(array);
// some error message
return;
}
array = temp_array;
// skipping section of code, which reads numbers from a file and loads them into an array
// amount of numbers read can be 0 to whatever
free (array); // free array or temp_array?
此外,如果尝试为其分配内存的指针为 NULL,是否可以使用 realloc 分配内存块(换句话说,我是否需要先使用 malloc 分配内存,然后使用 realloc 调整大小,或者可以我跳过 malloc)?
【问题讨论】:
标签: c malloc free realloc pointer-to-pointer