I am facing a problem while coding Linked List implementation in c++. Whenever I am trying to add an element I am getting Segmentation Fault error.
#include <iostream>
class node{
public:
int data;
class node *next;
};
class LinkedList {
public:
node *head;
LinkedList(int num);
void add(int number);
void display();
};
const int null = 0;
LinkedList::LinkedList(int num) {
// TODO Auto-generated constructor stub
std::cout<<"Constructor Called"<<std::endl;
head->data = num;
head->next = null;
std::cout<<"Constructor Call completed"<<std::endl;
}
void LinkedList::add(int num) {
struct node *n=new node;
n->data = num;
n->next = null;
struct node *current = head;
while (current->next != null) {
current = current->next;
}
current->next = n;
}
void LinkedList::display() {
std::cout<<"Display"<<std::endl;
struct node *current = head;
while (current!= null) {
std::cout << current->data << "->";
current = current->next;
}
std::cout << "null"<<std::endl;
}
int main() {
LinkedList l(1);
l.display();
l.add(2);
l.display();
return 0;
}
Please look into the gdb debug logs: node n is not referencing to any memory location. So it could not be initialized. Please let me know in case you require any further information.
Thanks in advance!
struct node *n=new node;
Constructor Called Constructor Call completed Breakpoint 1, main () at SampleCPP.cpp:60 60 l.display(); (gdb) s LinkedList::display (this=0xbffff03c) at SampleCPP.cpp:48 48 std::cout (gdb) n 51 while (current!= null) { (gdb) n 52 std::cout data "; (gdb) n 53 current = current->next; (gdb) n 51 while (current!= null) { (gdb) n 55 std::cout null 56 } (gdb) n main () at SampleCPP.cpp:61 61 l.add(2); (gdb) s LinkedList::add (this=0xbffff03c, num=2) at SampleCPP.cpp:38 38 struct node *n=new node; (gdb) print n $2 = (node *) 0x0 (gdb)