Hemant Bhargava Hemant Bhargava - 1 month ago 8
C++ Question

Returning address of local variable and program still work

Lets say this is the snapshot I want to talk about. In this code, main function calls 'foo' which returns address of locally declared variable 'a'. I was under the impression that locally declared variables de-allocates the memory when they go out of scope. Variable 'a' should be de-allocated after call to foo is done and there should not be anything left related to 'a'. But in this case, it seems to be breaking that basic assumption. What is going on underneath?

int* foo() {
int a = 5;
return &a;
}

int main() {
int* p = foo();
// Prints 5
std::cout << "Coming from foo = " << *p << std::endl;
*p = 8;
// Prints 8
std::cout << "Setting explicitly = " << *p << std::endl;
}

Answer

It depends on your machine/compiler what value is printed. The deallocation of stack doesn't mean what was there earlier got erased. It just means that area has become invalid. That means the behavior is not guaranteed when you try to access those addresses. In your case, it just happens that the location used for storing the local variable a has not been overwritten.