嵌套的while循环内存泄漏,即使我在两个循环之后都释放了

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

Valgrind告诉我,我的内存正在泄漏在两个不同位置分配“结果”的位置。我在代码中释放了结果。我真的被卡住了。有趣的是,注释掉第二个免费磁盘并不会加重我的内存泄漏,这意味着它实际上没有做任何事情。有想法吗?

void index_build(const char *pathname, index_t *index) 
{
    char *filename = count_malloc(strlen(pathname) + 5);
    int id = 1;
    sprintf(filename, "%s/%d", pathname, id);
    FILE *fp = fopen(filename, "r");
    while (fp != NULL) {
        char *url = count_malloc(200);
        fgets(url, 50000, fp);
        char *depth = count_malloc(sizeof(fgets(depth, 5000000, fp)) + 1);
        fgets(depth, 500000, fp);
        int d = atoi(depth);
        webpage_t *page = pageDir_load(url, d);
        int pos = 0;
        char *result = count_malloc(sizeof(webpage_getNextWord(page, &pos)) + 1);
        result = webpage_getNextWord(page, &pos);
        while (result != NULL) {
            if (index_find(index, result) == NULL) {
                counters_t *new = counters_new();
                counters_add(new, id);
                index_insert(index, result, new);
            }
            else {
                counters_t *current = index_find(index, result);
                counters_add(current, id);
            }
            free(result);
            result = count_malloc(sizeof(webpage_getNextWord(page, &pos)) + 1);
            result = webpage_getNextWord(page, &pos);
        }
        free(result);
        id++;
        fclose(fp);
        sprintf(filename, "%s/%d", pathname, id);
        fp = fopen(filename, "r");
        free(depth);
        webpage_delete(page);
    }
    free(filename);
}

valgrind错误:

54 bytes in 6 blocks are definitely lost in loss record 1 of 2
==3516925==    at 0x483980B: malloc (vg_replace_malloc.c:309)
==3516925==    by 0x40227D: count_malloc (memory.c:54)
==3516925==    by 0x401572: index_build (indexer.c:63)
==3516925==    by 0x40146C: main (indexer.c:46)
==3516925== 
==3516925== 495 bytes in 55 blocks are definitely lost in loss record 2 of 2
==3516925==    at 0x483980B: malloc (vg_replace_malloc.c:309)
==3516925==    by 0x40227D: count_malloc (memory.c:54)
==3516925==    by 0x40161B: index_build (indexer.c:76)
==3516925==    by 0x40146C: main (indexer.c:46)
c memory-leaks valgrind
1个回答
0
投票

我为所有malloc分配了代码,并释放了这样的代码:

egrep "malloc|free"

我得到了这些结果:

char *filename = count_malloc(strlen(pathname) + 5);
    char *url = count_malloc(200);
    char *depth = count_malloc(sizeof(fgets(depth, 5000000, fp)) + 1);
    char *result = count_malloc(sizeof(webpage_getNextWord(page, &pos)) + 1);
        free(result);
        result = count_malloc(sizeof(webpage_getNextWord(page, &pos)) + 1);
    free(result);
    free(depth);
free(filename);

以上,我看到url永远不会被释放。

© www.soinside.com 2019 - 2024. All rights reserved.