Where is the memory leak in this code?
I cannot understand the memory leak in my code
My Valgrind gives
==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)
And this is the code where the memory leak occurs
/*
* 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);
}
All allocated memory is freed from memory leak. I cannot understand, please help?
+3
user4927715
source
to share