Monday, 12 August 2013

C++, Accessing a non-global variable declared inside other method

C++, Accessing a non-global variable declared inside other method

This code takes value returned from a function, creates and puts it in a
new address space called variable 'b'
int main()
{
int b;
b = topkek();
std::cout << &b;
};
int topkek()
{
int kek = 2;
return kek;
};
Now I understand because variable kek was inside of topkek method I can
not access it from main() method. With C++ and pointers, I figured out how
I could access a variable declared inside a method even after the method
has terminated, look at this code.
int main()
{
int * a;
a = topkek(); //a is now pointing at kek
std::cout << *a; //outputs 2, the value of kek.
*a = 3;
std::cout << *a; //output 3, changed the value of kek.
std::cin >> *a;
};
int * topkek()
{
int kek = 2;
int* b = &kek; //intializing pointer b to point to kek's address in
stack
return b; //returning pointer to kek
};
Is this method safe? Would the compiler prevent kek's address space being
overwritten later in code because it still understand it's being used?

No comments:

Post a Comment