I'm aware that asprintf() allocates memory and this needs to be freed after it's called. I added free statements for the pointers provided to asprintf (after they're used), yet valgrind reports that I still have memory leaks:
==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
...so now all the bytes are freed but I still have allocated blocks? How do I fix this. Also here's the section of code where this is going on (including hw2pt2.c:235 & 236, which are the asprintf lines).
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" is freed later in the program