我知道 realloc
会在必要时释放内存,我知道 C 的第三条规则 - “对于每个 malloc
必须有一个相等且相反的 免费
”...但这两者如何协同工作?
最好用代码描述这种情况:
int main()
{
myStruct **myStructArray;
int i, num_elements;
num_elements = getnumber(); // gets value for num_elements
myStructArray = (myStruct **) malloc(num_elements * sizeof(myStruct*));
for (i=0; i<num_elements; i++)
myStructArray[i] = (myStruct *) malloc(sizeof(myStruct));
// so far so good...
num_elements = getnumber(); // gets new, LOWER value
myStructArray = realloc(myStructArrary, num_elements * sizeof(myStruct*));
// rest_of_code, and necessary free loop for myStructArray etc...
}
显然以上只是一个片段,但是一个片段画出一千个字。
这会造成内存泄漏吗?我知道对 realloc
的调用将释放指针的内存,但我可以看到支持和反对仍有大量内存被遗忘的可能性的争论。
可以通过将 int number_elements_new
合并到代码中并在调用 之前循环
以释放(现在为 NULL)指针。free
-ing 多余的 myStruct
来避免泄漏realloc
如果 realloc
完成了笨拙的工作并释放了所有相关的内存,那就太好了,否则我必须仔细搜索以确保没有遗漏任何东西 - myStruct
本身包含分配的内存等。
感谢您的建议...
最佳答案
malloc
、realloc
和 free
不知道内存的用途。如果您正在使用内存来存储指向其他动态分配内存的指针,那么您需要整理一下!
另请注意,您在代码片段中使用 realloc
的方式可能不安全。如果 realloc
失败,它会保留未释放的原始内存,并返回 NULL
。最佳做法是将返回值分配给一个临时指针,然后进行检查。参见例如http://www.c-faq.com/malloc/realloc.html .
关于c - realloc 和 malloc 过去的幽灵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14523690/