In C++, local variables are those variables that are declared inside a function or a block. Generally, we cannot access these variables outside its scope using the variable name but there are some exploits that we can use to do that.
In this article, we will see how to access a local variable memory outside its function or scope.
Access Local Variable Outside its Scope in C++
We can access the local variable memory by simply setting a pointer to the local variable memory and then accessing this pointer from outside of its scope.
// C++ program to illustrate how to access the local // variable memory outside its scope using pointer. #include <iostream> using namespace std;
// driver code int main()
{ int * ptr = NULL;
// block/scope start
{
// local variable
int var = 20;
cout << "Address of local variable: " << &var
<< endl;
// taking memory address
ptr = &var;
}
// block/scope end
cout << "Accessing Memory of Local Variable Outside "
"the Scope\n";
cout << "Value at " << ptr << ": " << *ptr;
return 0;
} |
Address of local variable: 0x7ffcd9e40444 Accessing Memory of Local Variable Outside the Scope Value at 0x7ffcd9e40444: 20
But accessing local variable is not recommended as it may cause segematation faults or other undefined errors as we are accessing memory which we do not have ownership of.