c++pointersreturn-valuepass-by-referencepass-by-pointer

The address always returned is 0 instead of the actual value


Here is the simple code:

int *ad_return()
{
    int a=600;
    cout << &a << endl;
    return &a;
}

int main()
{
    cout << ad_return();
    return 0;
}

The output is unexpected. The first cout prints an address that looks like a address but the cout that is in the main prints a legit 0. I couldn't find an explanation anywhere.


Solution

  • Based on what I have experimented, I have concluded the following:

    Since the address of a local variable that has already went out of scope is undefined, it seems that gcc and g++ decided to implement a feature that sets this to zero (probably to make sure that the code segfaults instead of generating thoroughly bizarre behaviour). It does not do this in clang, but the value is undefined so both of these compilers are operating in accordance with the standard.