returning address of a local variable

Hi,
I know that this code is wrong because it returns the address of local variable which no longer exist after function:
1
2
3
4
5
int *f1()
{
    int x = 2;
    return &x;
}

However, why this one does not show problem and runs fine, here the pointer p is also a local variable:
1
2
3
4
5
6
7
int *f2()
{
    int x = 2;
    int *p;
    p = &x;
    return p;
}
Define "runs fine". You can execute a function call to f2() just as you can execute a function call to f1(), that's not a problem. The behavior of a program that dereferences the pointer returned by either of those function calls is undefined.
f2() returns pointer to 2 which is supposed to be. Compiler does not show any error.
1
2
3
4
5
int main()
{
    int *x = f2();
    cout << *x << endl;
}

output is 2
Last edited on
the output of "2" is just one of the many possible results of executing an undefined program. See http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794
There's no guarantee that it will work correctly as it is undefined behavior. The two examples are functionally the same. The address returned will still contain the location of where x was, x's value (2) will probably still be there after the function returns. But it could be re-purposed at any time so it becomes unsafe to use.
Funny but very illustrative link. I will read it all. Thanks for explaining it. By-the-way, when a function returns a value, that is also related with the local memory defined within the function because 2 is stored somewhere in the memory. Then, why does the "value return" has no problem?
When a function returns a value, it is not related to memory: it has no address. Try:

1
2
3
4
5
6
7
8
#include <iostream>
int f3() {
    return 2;
}
int main() 
{
   std::cout << "The address of the value returned by f3() is " << &f3() << '\n';
}

that won't compile
Topic archived. No new replies allowed.