Zablas
Zablas

Reputation: 322

Simple C++ program crashes once using node pointers

So I never actually learned graph theory but I had seen some examples so I want to try something myself. I made a simple program which looks like this:

struct node
{
   node* prev;
   node* next;
   int num = 0;
   /*node()
   {
      prev = new node();
      next = new node();
   }*/
};

int main()
{
   node* curr = new node();
   curr->num = 1;
   curr->prev = curr;
   curr = curr->next;
   curr->num = 2;

   return 0;
}

When I uncomment the constructor it crashes on the first line of main(). When it's commented out it crashes the "curr->num = 2;" line. I don't actually know why that happens and would like to find out. Thanks!

Upvotes: 1

Views: 72

Answers (3)

UKMonkey
UKMonkey

Reputation: 6983

node()
{
    prev = new node();
    next = new node();
}

On creation of a new node, you create 2 more nodes. This process never stops, its a recursive ctor.

Upvotes: 3

Matteo Tosato
Matteo Tosato

Reputation: 235

Actually, the program crash at the cum->num = 2 because you have set curr to curr->next that is NULL.

If you uncomment the ctor the program will crash again because you are creating an infinite cycle of initializations. Look at the stacktrace:

I can suggest a working example:

struct node
{
    node* prev;
    node* next;
    int num = 0;
};

int main()
{
    node* curr;

    // Make a root node:
    node* root = new node();
    root->num = 1;
    // Create a child node
    root->next = new node();

    // Set '2' at the child node
    curr = root->next;
    curr->num = 2;
    // Create a child of the child node
    curr->next = new node();

    // Set '3' at the child node of the child node
    curr = curr->next;
    curr->num = 3;

    // Etc...

    return 0;
}

Debug it to understand better:

enter image description here

Upvotes: 1

Samer Tufail
Samer Tufail

Reputation: 1884

Your first problem is as mentioned by UKMonkey.

The second one would be

   curr = curr->next;
   curr->num = 2;

You dont allocate memory to the next after you move to curr->next so you cant assign a value to a location which hasn't been initialised.

Upvotes: 1

Related Questions