Can a local variable's memory be accessed outside its scope?

I have the following code.
#include <iostream>

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

int main()
{
int* p = foo();
std::cout << *p;
*p = 8;
std::cout << *p;
}
#include <iostream>

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

int main()
{
int* p = foo();
std::cout << *p;
*p = 8;
std::cout << *p;
}
And the code is just running with no runtime exceptions! The output was 58 How can it be? Isn't the memory of a local variable inaccessible outside its function?
4 Replies
Embedded Shiksha
In the foo function, you're creating a local variable a and returning a pointer to it. Once the foo function exits, the local variable a goes out of scope, and its memory is no longer guaranteed to be valid. It may be overwritten by other function calls or operations. In your main function, when you dereference the pointer p to read and modify the value, you're accessing memory that's no longer guaranteed to be associated with the variable a. This is undefined behavior, and it can lead to unpredictable and inconsistent results. The fact that it outputs "58" is simply a manifestation of undefined behavior, and it can vary from one compiler or platform to another.
techielew
techielew8mo ago
Thanks @embeddedshiksha_39035. What toolchains do you typically use?
Yash Naidu
Yash Naidu8mo ago
I agree with Embedded Shiksha. I would also like to give the code analysis from my side. In the function foo, 'a' is a local variable with automatic storage duration, meaning its lifetime is limited to the duration of the function call. When foo returns, the lifetime of 'a' ends, and any pointer pointing to its location becomes a dangling pointer. Accessing such a pointer, as done in main, results in undefined behavior. Although 'a' is no longer valid on the stack, the address where a was initialized to 5 might still be holding 5. As per the output, the behaviour should be undefined. When accessing the *p after the function call, it should possibily give a warning or a seg fault. The memory location is present (it's part of the stack), but it's not valid for 'a' anymore.
Embedded Shiksha
its GNU