Home > Enterprise >  C access statically allocated objects' members
C access statically allocated objects' members

Time:12-22

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;
\
}

CodePudding user response:

Suppose you own a plot of land and bury a body in it. Later you sell the land to someone else. Then you remember the body and freak out, so you go back and dig it up in the night. Luckily for you, it's still there.

Yes, you were trespassing, and there was no guarantee you'd find it, but since the new owner hadn't done anything yet to their land, it was still intact.

  • Related