这段代码中的内存泄漏在哪里?

时间:2015-05-24 23:34:26

标签: c memory-leaks

我无法弄清楚代码中的内存泄漏 我的Valgrind正在给予

==26373== HEAP SUMMARY:
==26373==     in use at exit: 24 bytes in 1 blocks
==26373==   total heap usage: 7 allocs, 6 frees, 136 bytes allocated
==26373== 
==26373== 24 bytes in 1 blocks are definitely lost in loss record 1 of 1
==26373==    at 0x4C2ABBD: malloc (vg_replace_malloc.c:296)
==26373==    by 0x400592: graph_init (in /media/goutam/CommonPartition/My Research/DataStructures/Graphs/main)
==26373==    by 0x40081D: main (in /media/goutam/CommonPartition/My Research/DataStructures/Graphs/main)

这是创建内存泄漏的代码

/*
 * Allocates memory for graph,adjacency matrix and nodes 
 */
graph_t* graph_init(int n){
    graph_t *graph = malloc(sizeof(graph_t));
    graph->count_nodes = n;

    /* Creating adjacency matrix and nodes of required size */
    graph->adjacency_matrix = malloc(sizeof(int*)*n);  
    graph->nodes = malloc(sizeof(struct Node*)*n);


    int i;
    for(i = 0 ; i < n; i++){
        // Allocating memroy for members of adjacency matrix and nodes
        graph->adjacency_matrix[i] = malloc(sizeof(int)*n); 
        graph->nodes[i] = malloc(sizeof(struct Node)*n);
        graph->nodes[i]->data = NULL;
        graph->nodes[i]->id = i; 

    }
    return graph;
}

/*
 * Frees memory for a node and stored data
 */
static void deletenode(struct Node *node){
    free(node->data);
    free(node);
}

/*
 * Frees memory for graph,adjacency matrix and nodes 
 */
void graph_destroy(graph_t *graph){
    int **adjacency_matrix = graph->adjacency_matrix;
    struct Node **nodes = graph->nodes;
    int i;
    for(i = 0;i < graph->count_nodes;i++){
        free(adjacency_matrix[i]);
        deletenode(nodes[i]);       
    }
    free(adjacency_matrix);
    free(nodes);
}

分配内存的所有东西都被释放了内存泄漏。我无法弄清楚请帮忙吗?

1 个答案:

答案 0 :(得分:6)

你还没有释放graph。至少不在您展示的代码中。