c++ - Why do I get a segementation fault while calculating the one's complement of a binary number? -
i have written c++ code store binary number using doubly linked list lsb stored in head node.
whenever enter '0' in head node segmentation fault while calculating one's complement, not have problem when enter '1' in head node.
my code:
#include<iostream> using namespace std; class node { int bin; node *prev,*next; public: node(int b) { bin=b; prev=null; next=null; } friend class ii; }; class ii { node *head,*tail; int digits; public: ii() { head=null; tail=null; } void dig() { cout<<"enter number of digits: "; cin>>digits; if(digits<2) { cout<<"please enter more digits: "; cin>>digits; } else{} } void create() { int y; if(head==null) { node *q; cout<<"enter binary digit: "; cin>>y; if(y<0||y>1) { cout<<"enter again: "; cin>>y; } q=new node(y); head=q; head->next=null; head->prev=null; } else { cout<<"ll created"; } } void insert() { node* temp=head; node* q; int i,y; i=1; while(i<digits) { cout<<"enter next digit"; cin>>y; if(y<0||y>1) { cout<<"please enter again: "; cin>>y; } else { q=new node(y); temp->next=q; q->next=null; q->prev=temp; tail=q; temp=temp->next; i++; } } } void disp() { node *temp=tail; while(temp!=null) { cout<<temp->bin; temp=temp->prev; } cout<<endl; } void neg() { node *temp=tail; while(temp!=null) { if(temp->bin==0) { cout<<"1"; temp=temp->prev; } if(temp->bin==1) { cout<<"0"; temp=temp->prev; } } cout<<endl; } }; int main() { ii a; a.dig(); a.create(); a.insert(); a.disp(); a.neg(); return 0; }
output:
enter number of digits: 4 enter binary digit: 1 enter next digit1 enter next digit0 enter next digit0 0011 1100
and:
enter number of digits: 4 enter binary digit: 0 enter next digit0 enter next digit1 enter next digit1 1100 segmentation fault (core dumped)
somebody please explain why happening.
as nathan noted, debugger key tool programmer. stepping through program line line , looking problem key skill success.
i used couple of tools reproduce problem. 'gdb' debugger on linux. 'valgrind' linux tool variety of error including bad memory access.
valgrind pointed neg function.
void neg() { node *temp=tail; while(temp!=null) { if(temp->bin==0) { cout<<"1"; temp=temp->prev; // temp first node temp->prev == nullptr } // missing 'else' statement here? if(temp->bin==1) // crash here accessing nullptr { cout<<"0"; temp=temp->prev; } } cout<<endl; } };
i added 'else' statement , program worked excepted test cases.
there may other errors, test code well. investigate 'unit testing' more testing.
Comments
Post a Comment