Valgrind在asprintf()

时间:2017-10-11 18:02:16

标签: c pointers malloc valgrind asprintf

我知道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 - “*结果”稍后在程序中被释放

0 个答案:

没有答案