C++ access statically allocated objects’ members

  allocation, c++, memory-management, object

So I am trying to understand the state of the memory when I run the below code. From my understanding, the two sub-trees left and right that are initialized within the if-statement should be considered non-existent once the if-block ends. However, when I run this code, the output from within the if-block is the same as the output after the if-block. I thought this might be due to the system not actually removing what is allocated, instead simply updating a static memory pointer. So I allocate a large array in hopes of this overwriting anything that could potentially still exist after the if-block. However, this doesn’t seem to have any effect on the output. When I instead call the test function, on returning to main, the access to the sub-trees’ val members outputs some random value. This is in line with what I would expect.

Could someone either explain what is happening. Why does a block not seem to delete any locally allocated memory, while a function does appear to?

#include<iostream>

using namespace std;

class Tree {
    public:
    Tree(int init_val) : val{init_val} {}; 
    Tree() = default;
        Tree* left = nullptr;
        Tree* right = nullptr;
        int val;
};

void test(Tree* const tree) {
        Tree left(10);
        Tree right(20);
        tree->left = &left;
        tree->right = &right;
        cout << "inside function:" << endl;
        cout << "left = " << tree->left->val << endl;
        cout << "left = " << tree->right->val << endl;
}

int main(int argc, char const *argv[]) {
    Tree root;
    int input;
    cin >> input;
    if(input > 10) {
        Tree left(10);
        Tree right(20);
        root.left = &left;
        root.right = &right;
        cout << "inside if-statement:" << endl;
        cout << "left = " << root.left->val << endl;
        cout << "left = " << root.right->val << endl;
    }
    int arr[1000000];
    //test(&root);
    cout << "outside test and if-block:" << endl;
    cout << "left = " << root.left->val << endl;
    cout << "left = " << root.right->val << endl;

}

Source: Windows Questions C++

LEAVE A COMMENT