为什么我无法释放内存?无效的free()/ delete / delete [] / realloc()

问题描述 投票:0回答:1

我正在尝试改善难看的C代码,这会导致内存泄漏。Valgrind点数:

==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很长,但是删除其他部分后,可以这样显示:

/* 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输出:

==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)

您能给我一个建议我做错了什么吗?我应该如何释放由malloc保留的内存?

c gcc memory memory-leaks valgrind
1个回答
1
投票

您无法释放它,因为您被拒绝:

word = "<unk>";

现在word不再指向您分配的内存,它指向此文字字符串。您有内存泄漏,尝试释放它时出错。

无需在那里重新分配word。只需将文字字符串写入文件即可。

if (use_unk_vec) {
    fprintf(fout, "<unk>");
}
© www.soinside.com 2019 - 2024. All rights reserved.