我的程序正在读取一个文件(test.txt,它仅包含 2 个字符串和一个空格,例如:“Hello World”),当我使用 calloc 时,它会在使用 valgrind 时导致内存泄漏。问题是我在第二次内存分配中丢失了更多字节(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 个字符串,则会导致内存泄漏。
最佳答案
在运行时,您需要执行与 calloc 一样多的 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! */
关于c - 如何修复calloc时的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56307161/