我想拥有一个读取文件并以char字符串的char(string)数组返回特定行的函数。
我跑了Valgrind,它表明障碍物确实丢失了,我不明白为什么。
如果我在分配内存的同一块中直接调用frees,则所有内容都将释放。如果我在块外(在另一个函数中)执行此操作,则Valgrind肯定会丢失。
我丢失了字节的代码:
int read_file(char *filename, char * search, char **data)
{
int counter = 0;
int size = 1;
FILE *file;
file = fopen(filename, "r");
char c[100];
while(fgets(c,100, file))
{
if(strstr(c,search))
{
while(fgets(c, 100, file))
{
if(c[0] == '[')
{
break;
}
if(c[0] == '\n')
{
continue;
}
if(counter+1 > size)
{
data = realloc(data,++size);
}
data[counter] = malloc(sizeof(**data)*(strlen(c)+1));
memcpy(data[counter], c, strlen(c)+1);
counter++;
}
}
}
fclose(file);
return size;
}
void free_pointer(char **data, int size)
{
for(int i = 0; i < size; ++i)
{
free(data[i]);
}
free(data);
}
int main()
{
char **data = malloc(sizeof(*data));
int x = read_file("test.txt", "omg", data);
// for(int i = 0; i < x; ++i)
// {
// printf("%s", data[i]);
// }
free_pointer(data,x);
return 0;
}
Valgrind显示以下内容:
泄漏摘要:
== 17349 ==绝对丢失:3个块中的20个字节
== 17349 ==间接丢失:0个字节(0块)
== 17349 ==可能丢失:0字节,共0块
== 17349 ==仍可访问:0个字节(0块)
== 17349 ==已禁止:0字节,0块
当我在此处添加自由行时:
if(counter+1 > size)
{
data = realloc(data,++size);
}
data[counter] = malloc(sizeof(**data)*(strlen(c)+1));
memcpy(data[counter], c, strlen(c)+1);
//if i add this
free(data[counter]);
counter++;
free(data);
fclose(file);
return size;
Valgrind显示以下内容:
堆摘要:
== 17459 ==在出口处使用:0字节,0块中
== 17459 ==堆总使用量:8个分配,8个空闲,分配的4,684个字节
Valgrind的第一个错误:
Valgrind erros:
==22271== Invalid read of size 8
==22271== at 0x10946C: main (in main)
==22271== Address 0x4a34480 is 0 bytes inside a block of size 8 free'd
==22271== at 0x4837D7B: realloc (vg_replace_malloc.c:826)
==22271== by 0x109299: read_file (in main)
==22271== by 0x10944B: main (in main)
==22271== Block was alloc'd at
==22271== at 0x483577F: malloc (vg_replace_malloc.c:299)
==22271== by 0x109426: main (in main)
由于我更改为正确的重新分配大小,所以出现了更多错误
==22271== LEAK SUMMARY:
==22271== definitely lost: 24 bytes in 1 blocks
==22271== indirectly lost: 17 bytes in 2 blocks
==22271== possibly lost: 0 bytes in 0 blocks
==22271== still reachable: 0 bytes in 0 blocks
==22271== suppressed: 0 bytes in 0 blocks