c - Segmentation fault (core dumped) while running the program -


#include<stdio.h> #include<string.h> #include<malloc.h> //#include<conio.h> struct list { char *value; struct list *link; }; struct list *arr[12];int val; int hf(char *item) { int sum,i=0; while(item[i]!='\0') {     sum+=item[i];     i++; } return sum%12; } void insert(struct list ** arr,char *item,int val) { struct list *temp,*r; r=*arr;      temp=(struct list *)malloc(sizeof(struct list));  strcpy((temp->value),item);   if(strcmp((r->value),null))   {       strcpy((r->value),(temp->value));       (r->link)=null;   }   else   {       while(r->link!=null)         r=r->link;       r->link=temp;       r=r->link;        strcpy((r->value),(temp->value));       r->link=null;    }  *arr=r;  } void main() {   struct list *li[12];int i=0;   for(i=0;i<12;i++)   {       li[i]=null;   }   char *item;int ret;   strcpy(item,"steve");   ret=hf(item);   insert(&li[ret],item,ret);   strcpy(item,"raj");   ret=hf(item);   insert(&li[ret],item,ret);   strcpy(item,"notes");   ret=hf(item);   insert(&li[ret],item,ret); } 

the above program implement array of linked list , im trying insert string value. when trying run program, there no errors tells segmentation fault(core dumped) please explain reason

the code

char *item;int ret; strcpy(item,"steve"); 

tries copy string literal "steve" uninitialised pointer. need allocate memory item. easiest way of doing hard-code suitably sized stack buffer

char item[50]; 

you have similar problem inside insert. solve in same way

struct list {     char value[50];     struct list *link; }; 

or dynamically allocate correct size of buffer inside insert

temp->value = malloc(strlen(item) + 1); if (temp->value == null) {     /* handle oom error */ } strcpy(temp->value, item); 

in latter approach, make sure free(node->value) when free list node. note freeing of dynamically allocated memory missing program, meaning leak memory allocated using malloc.

there 1 more bug in code - insert assumes arr pointer valid list* null. need update either main or assumption in insert here.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -