我用“valgrind --leak-check=full”测试了我的软件,它显示:
==90862== 7,627 bytes in 4 blocks are definitely lost in loss record 858 of 897
==90862== at 0x4C2FB55: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==90862== by 0xD64991C: concat(int, ...) (Client.cpp:150)
我不明白为什么,因为我在 calloc 之后使用 free()。 这是我的代码:
char* p = concat(2, buffOld, buff);
char *x;
while(true) {
x = p;
p = strstr(p,"\\final\\");
if(p == NULL) { break; }
*p = 0;
p+=7;
parseIncoming((char *)x,strlen(x));
}
free(p);
和“concat”函数:
char* concat(int count, ...)
{
va_list ap;
int i;
// Find required length to store merged string
int len = 1; // room for NULL
va_start(ap, count);
for(i=0 ; i<count ; i++)
len += strlen(va_arg(ap, char*));
va_end(ap);
// Allocate memory to concat strings
char *merged = (char*)calloc(sizeof(char),len);
int null_pos = 0;
// Actually concatenate strings
va_start(ap, count);
for(i=0 ; i<count ; i++)
{
char *s = va_arg(ap, char*);
strcpy(merged+null_pos, s);
null_pos += strlen(s);
}
va_end(ap);
return merged;
}
我做错了什么?
最佳答案
I can't understand why, because I use free() after calloc
是的,但是(如果我理解正确的话)你 free()
错误的指针。
您应该将 p
复制到另一个指针(在修改它之前)和 free()
保存副本。
看看你的代码
char* p = concat(2, buffOld, buff);
char *x;
while(true) {
x = p;
p = strstr(p,"\\final\\");
if(p == NULL) { break; }
*p = 0;
p+=7;
parseIncoming((char *)x,strlen(x));
}
free(p);
指针 p
是用 calloc-ed 指针初始化的,但是 while
cicle 修改它并仅在 p
为 时返回空
。
所以,当你调用
free(p)
你在打电话
free(nullptr)
--- 编辑 ---
I still don't understand it. I added free(x) at the end, and it crashes
我最初对 free(x)
的建议是我的错误,因为我没有指出 x
是用 初始化的事实p
值,但在 while
循环中被修改。再次感谢 Johnny Mopp 让我注意到它。
我建议使用另一个变量来记住p
的原始值(calloc()
返回的确切值)并释放这个值。
有点像
char* p = concat(2, buffOld, buff);
char *x;
char * const forFree = p; /* <--- saving calloc() returned value */
while(true) {
x = p;
p = strstr(p,"\\final\\");
if(p == NULL) { break; }
*p = 0;
p+=7;
parseIncoming((char *)x,strlen(x));
}
free(forFree);
关于c - 使用 calloc 和 free 后内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40917024/