简体   繁体   中英

Pointer to deallocated variable changes address

This code:

#include <iostream>

using namespace std;

int* fun()
{
    int a = 5;
    int* pointerA = &a;

    cout << pointerA << endl;

    return pointerA;
}

int main()
{

    int* p = fun();

    cout << p << endl;

    return 0;
}

Prints the following:

0x[some address]
0

I understand that the variable a is deallocated when the function fun() returns, but why does cout << p << endl; return 0? Shouldn't it still point to the same address in memory, even though variable is technically not there anymore? Is this a compiler feature or undefined behavior?

repro case

EDIT: I found the culprit. I am using CodeBlocks, and in this project's build options, there is a flag "optimize even more (for speed) [-O2]". If it is checked, I get 0 , and if I uncheck the flag, I get the same address 0x[some address] , which is expected behavior.

I apologize for not mentioning my IDE.

Accessing the return value of fun has implementation-defined behavior, as it returns an invalid pointer value (see the quote below, why). In particular platforms, it may even generate a runtime fault. So, p 's value is implementation-defined as well. Most likely, it will became invalid pointer value, so accessing it is implementation-defined.

basic.std/4 :

When the end of the duration of a region of storage is reached, the values of all pointers representing the address of any part of that region of storage become invalid pointer values. Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior .

It is probably a compiler feature. In this case it is very easy to see that the pointer returned by fun will be invalid and thus further usage of the pointer will result in undefined behaviour. If you try a different compiler it might be different. Eg for me in Visual Studio 2012 it does return the actual address instead of 0.

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