I'm doing an assignment for my C algorithms class and I have a memory allocation as follows:
Graph* new_graph = (Graph*)malloc(sizeof(Graph));
new_graph->adjacency_matrix = malloc(num_nodes*sizeof(int*));
for(int i = 0; i < num_nodes; i++) {
for(int j = 0; j < num_nodes; j++) {
new_graph->adjacency_matrix[i] = calloc(sizeof(int), num_nodes);
}
}
When I'm trying to free the memory I'm doing it as follows, but valgrind keeps saying I have lost 1,176 bytes in 42 blocks due to my calloc.
void delete_graph(Graph *g) {
for(int i = 0; i < g->num_vertices; i++) {
free(g->adjacency_matrix[i]);
}
free(g->adjacency_matrix);
free(g);
}
The size of num_nodes is 7, so I'm assuming only the first row is being freed or something, but I've tried freeing it with another for loop etc., but i keep getting the same errors. Would really appreciate any help with this thanks!
How can I free this 2D calloc'd array in C?
You can't.... because your allocation is wrong.
In the allocation this line
for(int j = 0; j < num_nodes; j++) {
seems wrong. You keep overwriting the same pointer as you only use i
as index and therefore generates memory leaks.
EDIT
Let's say that num_nodes
is 2
Then your code is doing:
new_graph->adjacency_matrix[0] = calloc(sizeof(int), num_nodes);
new_graph->adjacency_matrix[0] = calloc(sizeof(int), num_nodes); // LEAK
new_graph->adjacency_matrix[1] = calloc(sizeof(int), num_nodes);
new_graph->adjacency_matrix[1] = calloc(sizeof(int), num_nodes); // LEAK
So you are allocating memory and saving the pointer... fine, but the you overwrite the same pointer with a new allocation. That's a memory leak that can't be recovered.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.