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

Memory Leak within nested while loop even though I free after both loops

Valgrind 告诉我内存泄漏,其中 "result" 分配在两个不同的位置。我在我的代码中释放结果。我真的卡住了。有趣的是,注释掉第二个 free 并没有恶化我的内存泄漏,这意味着它实际上没有做任何事情。想法?

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)

我像这样为所有 malloc 和 frees 搜索了您的代码:

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 永远不会被释放。