Search code examples
c++memorysegmentation-faultallocation

i am always getting segmentation fault


i am always getting 10861 segmentation fault (core dumped) in c++ sorry i came from java it always says that head -> next how to allocate memory to that

#include <iostream>
using namespace std;

class Node
{
public:
  int data;
  Node *next;
};

class lisp
{
public:
  Node *head;
  void create(int d)
  {
    this->head->data = d;
    cout << head->data;
  }
  void insert(int d)
  {
    Node *n = head;
    Node *add;
    add->data = d;
    cout << head -> next << endl; 
  }
};

int main()
{
  lisp test;
  test.create(0);
  test.insert(1);
  test.insert(2);
  return 0;
}

Solution

  • You need to initialize the pointer before assigning some values to it. So, you need Node *add = new Node(); to do so. And suppose you want to append a new node to the list, maybe you need to keep track of the tail of the list (Node *tail). Every time you add a new node, you move the tail.

    #include <iostream>
    using namespace std;
    
    class Node
    {
    public:
      int data;
      Node *next;
    };
    
    class lisp
    {
    public:
      Node *head;
      Node *tail;
      void create(int d)
      {
        head = new Node();
        head->data = d;
        tail = head;
        cout << head->data << endl;
      }
      void insert(int d)
      {
        Node *add = new Node();
        add->data = d;
        add->next = NULL;
        tail->next = add;
        tail = add;
        cout << add->data << endl; 
      }
    };
    
    int main()
    {
      lisp test;
      test.create(0);
      test.insert(1);
      test.insert(2);
      return 0;
    }