c - how to free my singly linked list program? -


i have 2 questions regarding code:

  1. why isn't struct node *a,*b; working in create()? message: b used not initialized. not working in if statement.
  2. 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

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -