【发布时间】:2016-12-12 07:43:54
【问题描述】:
所以我有这个代码:
/* Dynamic Array Reader */
/* Parameters:
* n: Number of values to be read
*
* Returns: pointer to the dynamically allocated array
*/
int *dyn_reader(unsigned int n) {
int* array = malloc(n * sizeof (int));
if (!array)
return NULL;
else {
unsigned int num_read = 0;
printf("Enter %u integers so they can be put into this array\n", n);
while (num_read < n) {
num_read += scanf("%d", array + num_read);
}
}
return array;
}
/* Add to array */
/* Parameters:
* arr: Existing array of integers
* num: number of integers in the array before the call
* newval: new value to be added
*
* Returns: pointer to the allocated array
*/
int *add_to_array(int *arr, unsigned int num, int newval) {
int* newarray = realloc(arr, (num+1) * sizeof (int)); //allocate one more space
if (newarray == NULL) //Return original array if failed to allocate
return arr;
//free(arr); //free old array -- this throws an error when i try and free up the old array
newarray[num] = newval;
return newarray;
}
int main()
{
/* testing exercise. Feel free to modify */
int *array = dyn_reader(5);
array = add_to_array(array, 5, 10);
array = add_to_array(array, 6, 100);
array = add_to_array(array, 6, 1000);
return 0;
}
如您所见,主函数调用 dyn_reader 分配足够的内存以允许数组中有 n 个元素。它从用户那里读取整数并返回数组。
然后主函数调用 add_to_array 重新分配足够的内存以在数组中添加一个添加元素。如果不能,则返回原始数组。如果内存重新分配有效,我将 newval 添加到数组的末尾。在这种情况下,我使用一个新指针来存储新重新分配的数组的位置。当我尝试释放旧数组 (free(arr);) 时,怎么会出错。那个指针不是仍然指向堆上的内存,我不应该释放它吗?
【问题讨论】:
-
Realloc 如果它移动了内存以便能够扩展它,则在成功时释放旧分配。
-
realloc将分配新的内存量,如果成功,将复制原始内存块,然后释放原始块,最后返回指向新内存块的指针。如果不成功,则返回 NULL,但原始内存保持不变。 -
如果 realloc 设法扩展您的分配而不移动到不同的地址,那么 realloc 可以为您提供与 return 相同的指针,因此通过 free(arr) 您实际上会释放新重新分配的内存。
-
在指向内存的指针上调用 free,因为该指针可能指向垃圾,所以已经重新分配是未定义的行为。
-
因为
realloc释放了它,你不能释放它两次。