My program (its not complete but I would really like to know my error):
#include <iostream.h>
using namespace std;
class dcllnode
{
private:
int data;
dcllnode *next;
dcllnode *prev;
public:
dcllnode(int ele)
{
data = ele;
prev = next;
next = prev;
}
friend class dcll;
};
class dcll
{
private:
dcllnode *head;
public:
dcll()
{
head = NULL;
}
void create();
void inserts(int ele);
void inserte(int ele);
void inserta(int ele, int pos);
void insertb(int ele, int pos);
void dels();
void dele();
void dela();
void display();
};
void dcll::create()
{
if (head == NULL)
{
head = new dcllnode(0);
cout << "list is created";
}
else
{
cout << "list has already been created";
}
}
void dcll::inserts(int ele)
{
if (head == NULL)
cout << "please create the list first ";
else
{
dcllnode *x;
x = new dcllnode(ele);
x->prev = head;
x->next = head->next;
(head->next)->prev = x;
head->next = x;
cout << "list is modified";
}
}
void dcll::inserte(int ele)
{
if (head == NULL)
cout << "please create the list first ";
else
{
dcllnode *x;
x = new dcllnode(ele);
x->next = head;
x->prev = head->prev;
(head->prev)->next = x;
head->prev = x;
cout << "list is modified";
}
}
void dcll::dels()
{
if (head == NULL)
cout << "please create the list first ";
else
{
dcllnode *x;
head->next = x;
head->next = x->next;
(x->next)->prev = head;
x->next = NULL;
x->prev = NULL;
delete(x);
cout << "list is modified";
}
}
void dcll::dele()
{
if (head == NULL)
cout << "please create the list first ";
else
{
dcllnode *x;
head->prev = x;
head->prev = x->prev;
(x->prev)->next = head;
x->prev = NULL;
x->next = NULL;
delete(x);
cout << "list is modified";
}
}
void dcll::display()
{
if (head == NULL)
cout << "please create the list first ";
else
{
dcllnode *p = head->next;
while (p != head)
{
cout << "\n" << p->data;
p = p->next;
}
}
}
int main()
{
dcll l1;
l1.create();
l1.inserte(10);
l1.display();
l1.inserts(20);
return 0;
}
The segmentation problem is not occurring when I use only the create function. I would like to know how to solve such problems and how to avoid segmentation errors in future any information and/or help is appreciated.
You typically get segmentation faults when using illegal pointers (null or uninitialized pointers, or pointers pointing to unallocated or otherwise illegal memory).
In your case it's easy to see what one of the problems are, it's in the
dcllnode
constructor where you doWhen you do these assignments the pointers
next
andprev
are uninitialized, and their values are indeterminate. Assigning them to each other like this will not initialize them, just make them both have the same indeterminate value. Later when you dereference these pointers you will have undefined behavior leading to your segmentation fault and the crash.What you probably should to is to initialize both pointers to null:
[Note: In C++ don't use
NULL
, use eithernullptr
(preferred) or if you don't have it then plain0
.]