我无法理解如何在以下代码片段中正确释放我的内存:
char *func(char* s){
/* do something with s */
// pass s to function, create new string, return this string
s = function_allocating_mem(s);
// pass s to function, create new string, return this string
s = other_function_allocation_mem(s);
/* do other stuff again */
return s;
}
int main(void){
char str[] = "somestring";
str = func(str);
}
现在我分配了两次不同大小的内存。但是如果我做对了,我只是改变了指针地址并且永远不会释放内存。
我真的不知道,要谷歌什么才能找到一个例子
这是否正确,我该如何更改?
编辑: 我删除了函数的第二个参数。这没有必要,而且令人困惑。
最佳答案
当你在程序中从堆中分配内存时,你必须清楚地了解:
堆内存在您的程序中的分配位置。
堆分配内存的所有权如何从一个函数转移到下一个函数,以及
在程序结束前释放它的位置。
在您的情况下,假设 function_allocating_mem
和 other_function_allocation_mem
不在输入参数上调用 free
,您必须确保内存在这些函数中分配的在 fun
或 main
中释放。
char *func(char* s, const char* os){
char* s1 = NULL;
char* s2 = NULL;
/* do something with s and os */
// pass s to function, create new string, return this string
s1 = function_allocating_mem(s);
// pass s to function, create new string, return this string
s2 = other_function_allocation_mem(s1);
/* do other stuff again */
// Deallocate memory that was allocated by function_allocating_mem().
free(s1);
// Memmory allocated by other_function_allocation_mem is returned to the
// calling function.
return s2;
}
int main(void){
char str[] = "somestring";
// This is not legal anyway.
// str = func(str, "some other string");
char* s = fun(str);
// Use s ...
// Before returning from this function, deallocate memory
// that was allocated in the call to fun().
free(s);
}
关于c - 如果指针重定向,则释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27628011/