0

If I understand correctly, variables that are not dynamically allocated are supposed to be deleted at the end of their scope. However, I wanted to try it out with this code (which I think is not correct as I am supposed to use dynamic allocation) :

int* function()
{
    int a = 3;
    return &a;
}

int main(int argc, char const *argv[]) {
    int* a(function());
    std::cout << *a << std::endl; // prints 3
}

Why can I still access the value of the variable a by using the pointer returned by the function when it is supposed not to exist anymore ?

MaxV37
  • 530
  • 3
  • 14

2 Answers2

0

a and hence the return value from function has gone out of scope. You are just lucky.

Just be careful and compile with all the warnings enables - and take heed of those warnings.

Ed Heal
  • 57,599
  • 16
  • 82
  • 120
0

The fact that you can access the value is pure luck. The code has undefined behaviour (since the variable is destroyed) and the compiler can generate whatever it wants - but you cannot rely on it.

Jesper Juhl
  • 28,933
  • 3
  • 44
  • 66