c - how to free my singly linked list program? -
i have 2 questions regarding code:
- why isn't
struct node *a,*b;working increate()? message:b used not initialized. not working inifstatement. - if use
malloc()in normal program can use free ->free(variablename);, how go freeing singly linked list?
here's code:
#include<stdio.h> #include<conio.h> #include<malloc.h> struct node { int d; struct node *next; }*start=null;struct node *a,*b; void create() { a=(struct node *)malloc(sizeof(struct node)); printf("enter data : "); scanf("%d",&a->d); a->next=null; if(start==null) { start=a; b=a; } else { b->next=a; b=a; } } void display() { struct node *a; printf("\nthe linked list : "); a=start; while(a!=null) { printf("%d--->",a->d); a=a->next; } printf("null\n"); } void main() { char ch; { create(); printf("do want create : "); ch=getche(); } while(ch!='n'); display(); free(a); // don't know crt? }
you must free each element of list individually. each slice of memory has been allocated malloc must freed free.
instead of calling free(a) @ end of program, call freenodes().
void freenodes() { struct node *a; = start; while(a != null) { struct node *freenode = ; = a->next; free(freenode) ; } }
Comments
Post a Comment