[英]Is it necessary to free sub-pointer before calling realloc on pointer-to-pointer array to shrink its size?
For example, I have this C code:例如,我有这个 C 代码:
int len = 100;
int i;
// arr is pointer-to-pointer 2d array of char
char **arr = malloc(len * sizeof(char*));
for (i = 0; i < len; i++)
{
// Allocate the sub-pointer
arr[i] = malloc(len * sizeof(char));
...
}
...
// Is this part necessary?
for (i = 0; i < len; i++)
{
// Freeing the sub-pointer
free(arr[i]);
}
// Shrink the arr's size from 100 to 50
char** temp = realloc(arr, 50 * sizeof(char*));
...
Before to do realloc for arr
to shrink its size (from 100 to 50), is it necessary to free the arr
's sub-pointer?在对
arr
重新分配以缩小其大小(从 100 到 50)之前,是否有必要释放arr
的子指针?
for (i = 0; i < len; i++)
{
free(arr[i]);
}
Yes, you have to free all pointers if the reallocated array will have size that is less than the original size.是的,如果重新分配的数组的大小小于原始大小,则必须释放所有指针。 For example
例如
for (i = 50; i < len; i++)
{
free(arr[i]);
}
char** temp = realloc(arr, 50 * sizeof(char*));
C does not have destructors so you have manually to free all objects pointed to by the removed elements. C 没有析构函数,因此您必须手动释放已删除元素指向的所有对象。 Otherwise there will be memory leaks.
否则会出现内存泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.