我编写了一个C ++代码,用于使用双向链表存储二进制数,其中LSB存储在头节点中。
每当我在头节点输入'0'时,我在计算一个补码时会出现分段错误,但是当我在头节点输入'1'时我没有这个问题。
我的代码:
#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 the 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 the 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;
}
输出:
Enter the number of digits: 4
Enter binary digit: 1
Enter the next digit1
Enter the next digit0
Enter the next digit0
0011
1100
和
Enter the number of digits: 4
Enter binary digit: 0
Enter the next digit0
Enter the next digit1
Enter the next digit1
1100
Segmentation fault (core dumped)
有人请解释为什么会这样。
答案 0 :(得分:0)
正如Nathan所说,调试器是程序员的关键工具。逐行逐步完成程序并寻找问题是成功的关键技能。
我使用了一些工具来重现您的问题。 'gdb'是Linux上的调试器。 'valgrind'是一个Linux工具,它会查找各种错误,包括错误的内存访问。
Valgrind指出了neg函数。
void neg()
{
node *temp=tail;
while(temp!=NULL)
{
if(temp->bin==0)
{
cout<<"1";
temp=temp->prev; // likely temp is first node so temp->prev == nullptr
}
// missing an 'else' statement here?
if(temp->bin==1) // crash here accessing a nullptr
{
cout<<"0";
temp=temp->prev;
}
}
cout<<endl;
}
};
我添加了一个'else'语句,该程序作为测试用例的例外。
可能还有其他错误,请测试您的代码。调查“单元测试”以了解有关测试的更多信息。