-3

I started writing a binary tree and then came up with this example and I'm not sure what's going on. So here's the code:

#include<iostream>

using namespace std;

struct Node
{
    Node *left, *right;
    int key;
    Node()
    {
        left = NULL;
        right = NULL;
        key = 0;
    }
    Node(int key)
    {
        left = NULL;
        right = NULL;
        key = key;
    }
};

struct Tree
{
    Node* root;
    void Add(int k)
    {
        Node* t;
        t->key = k;
        root->left = t;
    }
    Tree(int key)
    {
        this->root = new Node(key);
    }
};

int main()
{
    Tree* tree = new Tree(5);
    tree->Add(4);
    cout<<tree->root->left->key;
    return 0;
}

Add function Add in Tree is whats confuses me. So, there is a pointer to Node object, but new keyword is not used and it appears to me that anyway there is memory allocated in the heap because I can reach the object. Shouldn't go out of scope and be destroyed? And why I can reach that object and print out its key?

user3199819
  • 71
  • 1
  • 5

3 Answers3

0

Probably that memory belongs to your program and nothing bad seems to happen because you are using so little memory. If you use more memory, some object will own that unallocated space and expect it to remain unmodified. Then this code will start giving you problems.

You are "dereferencing an uninitilized pointer". There are questions relating to this here and here, for instance. Your compiler may blow up if you do this, or it may not: the behaviour is undefined. Anything might happen, including the appearance that things are working.

Use new, like you should.

Richard
  • 56,349
  • 34
  • 180
  • 251
0

The code is invalid. In this function

void Add(int k)
{
    Node* t;
    t->key = k;
    root->left = t;
}

local variable t is not initialized and has indeterminate value. So the execution of the statement

    t->key = k;

results in undefined behaviour.

You correctly pointed to that there must be used operator new. For example

Node* t = new Node( k );

Nevertheless even in this case the function is invalid because it has to check whether the new key is less of greater than the key of root. Depending on the condition there should be either

root->left = t;

or

root->right = t;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

This line …

Node* t;

… is like:

Node* t = random_address;

It means that the next line …

t->key = k;

… is able to corrupt interesting memory locations.

dlask
  • 8,776
  • 1
  • 26
  • 30