c - Failed to add a node to linked list -


i make changes can't add more 2 nodes freez if 1 or 2 node work reason??? gave_up can nothing code till time

#include <stdio.h> #include <stdlib.h> #include <ctype.h>  struct info{     int num;     char name[15];     struct info *next; };  struct info *first,*current,*new_s; int struct_num; void add_struct(void);  int main(){     first=null;     add_struct();     puts("done");     add_struct();     puts("done");     add_struct();     puts("done");      return(0); } 

//struct add function

void add_struct(void){  new_s= malloc (sizeof(struct info)); if(!new_s){     puts("error");     exit (1); } if(first==null){    first = current= new_s;    first->next = null; }else{     current=first;      while(current->next!=null){         current=current->next;     }      current->next=new_s;     current=new_s; }  struct_num++; } 

the problem in code is

if( first==null){ first->next=new_s; 

if first null, should not dererefence it. logically wrong, , invokes undefined behaviour.

i think, want instead, (pseudo-code)

if(first == null){     first = new_s;     first->next = null; 

that said,

    current->next=new_s;     current=new_s; 

also looks problematic. second statement there wrong , not required, rather, can add like

   current->next = new_s;    current->next->next = null; 

finally, struct_num variable should global, per current usage.

note:

  1. the recommended signature of main() int main(void).
  2. please do not cast return value of malloc() , family in c.
  3. always check malloc() success before using returned pointer.

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -