c++ - Segmentation fault in creating Linked list -


in particular question trying find segmentation fault occurring. know there error while creating linked list of individual digits of k.

struct node {     int data;     struct node *next; };  int n1 = 0; int n2 = 0; int k = 1;  int calc(node *h) {     int sum=0;     for( ; h != null ; h = h->next)         sum=(sum*10)+h->data;     return sum; }  node* lists(node *heada, node* headb) {     n1 = calc(heada);     n2 = calc(headb);     int k = n1 + n2;     node *temp;     temp->data=k%10;      while(k>0)     {         k=k/10;         node *t1=new node;         t1->data=k%10;         t1->next=temp;         temp=t1;     }     return temp; } 

the error resides in following code:

node *temp; temp->data = k % 10; 

specifically, temp declared pointer points node struct, never given valid location in memory point to, contains garbage address refers non-writeable region.

if wanted fix this, first allocate region variable, this:

node *temp = new node; 

and mark released (by calling delete on it) later on when done it. recommend better formatting code, it's not convenient read viewer's perspective.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -