c++memory-managementheap-memoryclass-membersstack-memory

Why does declaring this variable in this method overwrite my class member (C++)?


I'm attempting to implement a linked list class. I have a struct called node that has data and a node*, as well as a linked list class that has a pointer to the head node of the linked list as a class member. I have written an insert method for the linked list class that inserts data into the nth position:

  void insert(int x, int n) {

        node* iterator = headNode;
        node* temp;
        temp->data = x;

        for (int i = 0; i < n-1; i++)
        {
            iterator = iterator->next;
        }
        temp->next = iterator->next;
        iterator->next = temp;
    }

However, when I do this, the head node class member is overwritten by temp. Using cout I found out that the line

        temp->data = x;

Is the line that overwrites it. Can someone explain why? By the way, I was able to fix the overwriting problem by declaring temp on the heap using new, but again, could someone please explain why?


Solution

  • @UnholySheep pointed out the in comments that I just declared a pointer without creating a node object, so what occurs is undefined behaviour. Thank you very much.