UfoKatze
UfoKatze

Reputation: 3

Value behind a pointer changes by printing it

I want to build up a simple binary-tree in C++ using pointers for each node pointing to the left child and to the right child. I set the root of the tree manually, then I add one number to the tree, but by printing its value in the main() the value of the variable behind the pointer changes its value.

#include <stdlib.h>
#include <iostream>
using namespace std;

struct Node
{
    int data = 0;
    Node *leftNode = NULL;
    Node *rightNode = NULL;
};

void insertNode(Node *node, int newData)
{
    cout << "Testing Node: " << node -> data << " | " << &(node -> data) << endl;
    //smaller (or equal) or bigger
    if (newData > node -> data)
    {
        if (node -> rightNode == NULL)
        {
            Node newNode;
            newNode.data = newData;
            node -> rightNode = &newNode;
        }
        else
        {
            insertNode(node->rightNode, newData);
        }
    }
    else
    {
        if (node -> leftNode == NULL)
        {
            Node newNode;
            newNode.data = newData;
            node -> leftNode = &newNode;
            cout << "Added Node: " << (node -> leftNode) -> data << " AT " << &(node -> leftNode -> data) << endl;
        }
        else
        {
            insertNode(node -> leftNode, newData);
        }
    }
}

int main()
{
    Node firstnode;
    firstnode.data = 42;
    Node *pointer = &firstnode;
    //insert nodes
    /*for (int i = 0; i < 10; i++)
    {
        cout << "Inserting new Element: " << (10 + i) << endl;
        int newI = 10 + i;
        insertNode(&firstnode, newI);
    }*/
    cout << "Inserting new Element: " << (10) << endl;
    int newI = 10;
    insertNode(&firstnode, newI);
    cout << "in main " << firstnode.leftNode -> data << " | " << &(firstnode.leftNode -> data) << endl;
    cout << "in main2 " << firstnode.leftNode -> data << " | " << &(firstnode.leftNode -> data) << endl;

    return 0;
}

Output:

Inserting new Element: 10
Testing Node: 42 | 0x61feec
Added Node: 10 AT 0x61fea8
in main 10 | 0x61fea8
in main2 6422216 | 0x61fea8

Do you have any ideas how to fix this?

Upvotes: 0

Views: 110

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

You are assigning pointers to non-static local variables. Non-static local variables will be invalid on returning from the function. You should dinamically allocate the nodes instead.

In the other words, you should use

Node* newNode = new Node;
newNode -> data = newData;
node -> rightNode = newNode;

instead of

Node newNode;
newNode.data = newData;
node -> rightNode = &newNode;

and also do like this for node -> leftNode.

Upvotes: 3

Related Questions