c++ - Segmentation Fault in deleting a node -
i have c++ code manipulates basic linked list - add new node, delete node , view list
//unix environment #include <iostream> #include <malloc.h> #include <stdlib.h> #include <stdio.h> #define clear() printf("\033[h\033[j") using namespace std; struct node { int val; node *next; }; struct node* head = null; void add_node(struct node *hea) { char f; int val; cout<<"enter value : "; cin>>val; if(head==null) { head = new(struct node); head->val = val; head->next = null; } else { node *traverser = hea; node *traverser_prev = null; while(traverser!=null) { traverser_prev = traverser; traverser=traverser->next; } traverser = new(struct node); traverser->val = val; traverser->next = null; traverser_prev->next=traverser; } cout<<"\nenter y return : "; cin>>f; while(f!='y') { cout<<"wrong entry.enter again : "; cin>>f; } return; } void view_list(struct node *hea) { char f; node *traverser = hea; while(traverser!=null) { cout<<traverser->val<<" "; traverser=traverser->next; } cout<<"\nenter y return : "; cin>>f; while(f!='y') { cout<<"wrong entry.enter again : "; cin>>f; } return; } void delete_node(node *hea) { char f; int del_value; cout<<"enter value deleted :"; cin>>del_value; node *traverser = hea; cout<<"ok1\n"; node* traverser_prev = null; cout<<"ok2\n"; while(traverser!=null) { if(traverser->val==del_value) { if(traverser==hea) { hea=traverser->next; cout<<"here cond1\n"; delete traverser; } else { traverser_prev->next = traverser->next; cout<<"here cond2\n"; } } else { traverser_prev = traverser; traverser = traverser->next; cout<<"here cond3\n"; } } cout<<"\nenter y return : "; cin>>f; while(f!='y') { cout<<"wrong entry.enter again : "; cin>>f; } return; } int main(int argc, char* argv[]) { while(1) { clear(); int choice; cout<<"pointer basics\n"; cout<<"1. add new element\n"; cout<<"2. view elements\n"; cout<<"3. delete element\n"; cout<<"4. exit\n"; cout<<"enter choice: "; cin>>choice; switch(choice) { case 1: add_node(head); break; case 2: view_list(head); break; case 3: delete_node(head); break; default:break; } if(choice==4) break; } }
however, whenever try delete node, throws me segmentation fault error core dumped. reason error?
one problem in delete_node
function pass list head by value, means pointer copied , inside function modify copy.
there 2 solutions: either don't use argument @ , use global variable, or pass argument by reference:
void delete_node(node*& hea)
Comments
Post a Comment