简体   繁体   中英

why pointer change exactly?

Any body has any idea why this code print a and not b ?

I tested that value of mainArea.root->rightBro changes when i cout something. but why?

#include<iostream>

using namespace std;

struct triangle{
    triangle *rightBro; 
};

struct area{
    triangle *root;
} mainArea;

void initialize(){
    triangle root;
    mainArea.root = &root;
}

int main()
{
        initialize();

        mainArea.root->rightBro = NULL ;

        if (mainArea.root->rightBro == NULL) cout << "a" << endl;
        if (mainArea.root->rightBro == NULL) cout << "b" << endl;      
        return 0;
}

You are storing a pointer to a local variable from within initialize . After the function returns that memory address is no longer valid to access through the pointer -- your program invokes undefined behavior (UB) when it dereferences mainArea.root inside main .

By definition, when UB is invoked anything can happen. What you see is some version of anything.

For practical programming purposes, please stop reading here. If you are curious why you are getting specifically this type of behavior, here's an explanation:

What happens in practice is that mainArea.root is left pointing to an "unused" address on the stack just after the stack frame for main . When you invoke operator<< a new stack frame is allocated, which overlaps the memory pointed to by mainArea.root . operator<< 's (stack-allocated) local variables overwrite the contents of that memory, which from the viewpoint of main results in seeing modified values.

This:

void initialize(){
    triangle root;
    mainArea.root = &root;
}

Is causing undefined behavior.

The variable triangle root; only lasts as long as the function is being executed. Once the function returns it no longer exists. Thus mainArea.root points at random mememory that can be re-used for anything.

Thus any use of mainArea.root after the function exits is undefined behavior. Meaning the application can do anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM