我知道 asprintf() 分配内存,这需要在调用后释放。我为提供给 asprintf 的指针添加了免费语句(在使用它们之后),但 valgrind 报告我仍然有内存泄漏:
==2697== HEAP SUMMARY:
==2697== in use at exit: 0 bytes in 12 blocks
==2697== total heap usage: 401 allocs, 389 frees, 15,015 bytes allocated
==2697==
==2697== 0 bytes in 6 blocks are definitely lost in loss record 1 of 2
==2697== at 0x4C2DB2F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2697== by 0x1094BB: experiment (hw2pt2.c:235)
==2697== by 0x4E416C9: start_thread (pthread_create.c:333)
==2697==
==2697== 0 bytes in 6 blocks are definitely lost in loss record 2 of 2
==2697== at 0x4C2DB2F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2697== by 0x1094CC: experiment (hw2pt2.c:236)
==2697== by 0x4E416C9: start_thread (pthread_create.c:333)
==2697==
==2697== LEAK SUMMARY:
==2697== definitely lost: 0 bytes in 12 blocks
==2697== indirectly lost: 0 bytes in 0 blocks
==2697== possibly lost: 0 bytes in 0 blocks
==2697== still reachable: 0 bytes in 0 blocks
==2697== suppressed: 0 bytes in 0 blocks
...所以现在所有字节都被释放了,但我仍然分配了块?我该如何解决。这也是发生这种情况的代码部分(包括 hw2pt2.c:235 和 236,它们是 asprintf 行)。
char *results = (char *)malloc(0);
for (int i = 0; i < NUM_THREADS; i++) {
char *str1 = (char *)malloc(0);
char *str2 = (char *)malloc(0);
asprintf(&str1, "\tProducer Thread %d slept %d times\n", i, r_vals[i]);
asprintf(&str2, "\tConsumer Thread %d slept %d times\n", i, r_vals[i+2]);
int len = strlen(str1)+strlen(str2)+strlen(results);
results = (char *)realloc(results, len*sizeof(char));
strcat(results, str1);
strcat(results, str2);
free(str1);
free(str2);
}
PS - “*results”稍后在程序中被释放