Can a local variable's memory be accessed outside its scope in C/C++?


Let us look at an example where you MIGHT be able to access a local variable's memory outside its scope.

Example

#include<iostream>
int* foo() {
   int x = 3;
   return &x;
}

int main() {
   int* address = foo();
   cout << *address;
   *address = 12;
   cout << *address;
}

Output

This might give the output −

3
12

As I've mentioned before, this code MIGHT work. We are simply reading and writing to memory that USED to be the address of x. In main, you're outside of foo's scope, the address is a pointer to some random memory area. In the above example, that memory area does exist and nothing else is using it at the moment. You don't break anything by continuing to use it(you won't be using another process' memory area or any other unauthorized memory area), and nothing else has overwritten it yet. Hence, the 3 is still there.

In a real program, that memory might have been re-used almost immediately and you'd break something by something like doing this. Such memory access bugs are very difficult to track and kill.

When you return from foo, the program tells the OS that x's memory is no longer being used and it can be reassigned to something else. If you're lucky and it gets reassigned, and the OS doesn't catch you using it again, then you can get away with it.

Updated on: 11-Feb-2020

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements