[英]How to fix memory leak when calloc
我的程序正在读取一个文件(test.txt,它只包含2个字符串和一个空格,如:“Hello World”),当我使用calloc时,它使用valgrind给我内存泄漏。 问题是我在第二个mem分配中丢失了更多的字节(b = calloc(11,sizeof(* b))。
我试过使用free()它没用
char str[1024];
char *a = NULL;
char *a = NULL;
int i = 0;
while(!feof(myfile)) {
//I used some codes here to skip "\r\n" which is working fine.
fscanf(myfile, "%10s", str);
i = strlen(str);
if(key_find(k,str) == NULL){
a = calloc(i,sizeof(*a));
strcpy(a,str);
key_insert(k,a);
}
fscanf(myfile, " ");
fscanf(myfile, "%10s", str);
if(key_find(k,str) == NULL){
b = calloc(i,sizeof(*a));
strcpy(b,str);
key_insert(k,a);
}
}
free(a); free(b);
当我的txt文件中只有2个不同的字符串时,它不会给我任何内存泄漏。 但如果我有超过4个字符串,那么它会给我内存泄漏。
在运行时,您需要执行与callocs一样多的free。 如果calloc在循环内,free也应该在循环内,例如:
a = calloc(i,sizeof(*a));
strcpy(a,str);
key_insert(k,a);
free(a); /* you need to free a when it is not needed */
然后
b = calloc(i,sizeof(*a));
strcpy(b,str);
key_insert(k,a); /* you should probably replace this by key_insert(k,b) */
free(b); /* don't need b anymore? free it! */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.