c++ - Segmentation fault while pointer assignment -
write programme reverse direction of given singly-linked list. in other words, after reversal pointers should point backwards.
i trying solve above problem. wrote functions insertion,search , deletion , printing singly linked list.
my print function follows
void print(list **l) { list *p=*l; for(int i=0;p;i++) { cout<<p->item<<endl; p=p->next; } }
it works fine printing values in list.
but in main function if same assignment this
list *p=*l;
it gives me segmentation fault. main function follow
main() { list **l; *l=null; int n; while(cin>>n) insert(l,n); list *p=*l; list *prev=null; list *next; while(p) { next=p->next; p->next=prev; prev=p; if(next==null) *l=p; p=next; } print(l); }
my insert function follows
void insert(list **l,int x) { list *p; p=(list *)malloc(sizeof(list)); p->item=x; p->next=*l; *l=p; }
what difference between assignment in print function , main function? why don't error in print function , segmentation fault in main function?
if function this
main() { list **l; *l=null; int n; while(cin>>n) insert(l,n); print(l); }
i not getting error able insert , print values of list.
when write
list **l; *l=null;
you're dereferencing invalid pointer, run undefined behavior.
inside function, you're passing valid pointer argument. example
list* l; void print(&l)
in case, &l
of type list**
- , points dangling list*
, dereferencing yield pointer (l
itself). l
isn't initialized, not reading ok.
c++ c
No comments:
Post a Comment