Can a local variable's memory be accessed outside its scope?
I have the following code.
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
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.
Thanks @embeddedshiksha_39035. What toolchains do you typically use?
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.
its GNU