c - Free an Array of Linked Lists -
so, have having problem freeing memory have allocated array of linked lists.
here typedef struct
:
typedef struct node { int id; int degree; int distance; int status; struct node *next; } node;
here create arrays
node *graph = malloc( sizeof(node) * n); if (graph == null) { printf("fatal error: out of memory!\n"); exit(1); } (int i=0; < n; i++) { n = create_node(i); graph[i] = *(n); } node *graph2 = malloc( sizeof(node) * n); if (graph2 == null) { printf("fatal error: out of memory!\n"); exit(1); } (int i=0; < n; i++) { n = create_node(i); graph2[i] = *(n); }
here create_node
:
node* create_node(int id) { // allocate memory construction node *n = malloc( sizeof (node) ); if (n == null) { printf("fatal error: out of memory!\n"); exit(1); } n->id = id; // set value identifies node n->distance = int_max; //we don't know teh source yet, distance infinity n->next = null; n->status = 0; homecoming n; }
here code seek free arrays
for (int i=0; < n; i++) { free_node(&graph[i]);//<---here graph = null; free_node(&graph2[i]); graph2 = null; }
and free_node
function:
int free_node(node *n) { node *tmp = malloc(sizeof(node)); while (n != null) {//<---here tmp = n; n = n.next; free(tmp); tmp = null; } homecoming 0; }
i segmentation fault @ lines of code labeled above "<---here" comment @ end of line. starts in free_node function called freeing graph[i]
.
you trying free struct
sending pointer of struct
assigning null
value pointers after first iteration, making them danging pointers.
check next fix:
for (int i=0; < n; i++) { free_node(graph + i); free_node(graph2 + i); }
c free
No comments:
Post a Comment