1
在下面的代码末尾,我需要将哪个指针插入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?
此外,是否有可能分配的内存块与realloc的,如果它试图为分配内存的指针为NULL(换句话说,我是否需要使用malloc第一分配内存,后来与调整其大小realloc,还是我可以跳过malloc)?
我不确定是否我写它是最好的方式,但代码来自一个函数,它读取文件中的整数并加载它们成阵列。无论如何,整数的数量可以是0。我在for循环外执行了malloc,循环遍历文件中的数字,并在for循环中使用realloc来增加数组的大小。我不确定是否可以在NULL指针上分配内存,所以这就是为什么我先调用malloc的原因。如果指针为NULL,是否可以使用realloc分配内存?即ptr = realloc(NULL,count * sizeof(int)); – Maya
好的。我会在包含记录数的文件中创建一个标题。然后函数首先读取头int,分配足够的内存然后读取所有的值。 – suspectus
好主意!没有想到这一点。 – Maya