Reputation: 168
I am trying to improve the ugly C code, which causes a memory leak. Valgrind points:
==19046== 1,001 bytes in 1 blocks are definitely lost in loss record 1 of 1
==19046== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==19046== by 0x109D0B: save_params (ugly.c:188)
save_params is very long, but after removing other parts it can be presented like this:
/* Save params to file */
int save_params(int nb_iter) {
char *word = malloc(sizeof(char) * MAX_STRING_LENGTH + 1); // <----- ugly.c:188 line
FILE *fid, *fout, *fgs;
for (a = 0; a < vocab_size; a++) {
if (fscanf(fid,format,word) == 0) {free(word); return 1;}
if (strcmp(word, "<unk>") == 0) {free(word); return 1;}
fprintf(fout, "%s",word);
//...
if (save > 0) {
fprintf(fgs, "%s",word);
if (fscanf(fid,format,word) == 0) {free(word); return 1;}
}
if (use_unk_vec) {
word = "<unk>";
fprintf(fout, "%s",word);
}
fclose(fid);
fclose(fout);
if (save > 0) fclose(fgs);
}
free(word); <--------- that free is "invalid"
return 0;
}
Valgrind output:
==19046== Invalid free() / delete / delete[] / realloc()
==19046== by 0x10AAC6: save_params (ugly.c:288)
==19046==
==19046== HEAP SUMMARY:
==19046== in use at exit: 1,001 bytes in 1 blocks
==19046== total heap usage: 78 allocs, 78 frees, 13,764,515 bytes allocated
==19046==
==19046== 1,001 bytes in 1 blocks are definitely lost in loss record 1 of 1
==19046== by 0x109D0B: save_params (ugly.c:188)
==19046== LEAK SUMMARY:
==19046== definitely lost: 1,001 bytes in 1 blocks
==19046== indirectly lost: 0 bytes in 0 blocks
==19046==
==19046== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
Could you give me a suggestion what I am doing wrong? How should I deallocate memory reserved by malloc?
Upvotes: 0
Views: 839
Reputation: 782614
You can't free it because yo udid:
word = "<unk>";
Now word
no longer points to the memory that you allocated, it points to this literal string. You have a memory leak, and an error when you try to free this.
There's no need to reassign word
there. Just write the literal string to the file.
if (use_unk_vec) {
fprintf(fout, "<unk>");
}
It's also unclear why you need the use malloc()
and free()
in the first place. Since you're only using word
in this function, you should just declare it as a local array:
char word[MAX_STRING_LENGTH + 1];
Upvotes: 3