DOR*_*pst 1 c pointers return-value
我写了一个小示例问题来了解内存分配和释放内存(以防止内存泄漏):
#include <stdlib.h>
long* foo(char str[]) {
long *nums;
nums = calloc(2,sizeof(long));
//something is happening depending on what's inside the char[]
nums[0] = 57347534;
nums[1] = 84757;
return nums;
}
int main() {
char str1[400] = "This is a test";
long* retValue = foo(str1);
//some lines of checking content of "retValue"
char str2[400] = "This is another test";
retValue = foo(str2);
//some more lines of checking content of "retValue"
char str3[400] = "This is a final test";
retValue = foo(str3);
//again some more lines of checking content of "retValue"
free(retValue);
}
Run Code Online (Sandbox Code Playgroud)
所以在我的main函数中,我使用三个char数组,我将传递给我的函数.这个函数有一个长值的num指针,其中有calloc两个.然后我只是根据内容计算一些数字str[]并返回nums.
我对此的疑问是:
nums?因为我在使用它之前无法释放它.retValue在最后一行释放是否正确?谢谢你的回答,这将有助于我更安全地使用指针!
你需要调用free每一个新的分配之前retValue(如果以前的分配是从哪里来的malloc,calloc或realloc).否则你会有内存泄漏.
每个分配必须匹配free简单明了.