Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

pointers

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?

like image 537
InstallGentoo Avatar asked Feb 13 '26 11:02

InstallGentoo


2 Answers

This is undefined behavior: once the function finishes, accessing a variable inside it by pointer or reference makes the program invalid, and may cause a crash.

It is perfectly valid, however, to access a variable when you go "back" on the stack:

void assign(int* ptr) {
    *ptr = 1234;
}
int main() {
    int kek = 5;
    cout << kek << endl;
    assign(&kek);
    cout << kek << endl;
}

Note how assign has accessed the value of a local variable declared inside another function. This is legal, because main has not finished at the time the access has happened.

like image 62
Sergey Kalinichenko Avatar answered Feb 15 '26 00:02

Sergey Kalinichenko


No it is not safe. After your function finished execution, you are not pointing to an int anymore but just to some random place in memory. Its value could be anything since it can be modified elsewhere in your program.

like image 34
teh internets is made of catz Avatar answered Feb 15 '26 02:02

teh internets is made of catz