Why does the c++ variable not get detleted immediately?

133 views Asked by At

I'd like to know why is it that the data that is pointed to when you return from a function, is not deleted immediately. In the snippet of code below,I expect that when I return the address of x to the pointer to initialise it when returning from function, the data stored in the address of x should be deleted immediately. However I am still able to get the correct value in main and then only after one more line of code does it suddenly turn into garbage? Why does this not happen immediately

int* function(int x)
{
    cout << x << endl; // This outputs 5 as expected
    return &x;
}

int main()
{
    int* a = function(5);


    cout << *a; // This still outputs 5. Why?
    cout << endl;

    cout << *a; // It is garbage here as expected
    cout << endl;

    return 0;
}

Thanks

4

There are 4 answers

6
SingerOfTheFall On BEST ANSWER

Returning the address of a local variable invokes undefined behavior. So, you're just lucky.

The local variable (allocated on the stack) gets deleted when it leaves it's scope, which in your case is when function() ends. However, after the variable leaves the scope, the memory it occupies is not rewritten immediately and unless that memory is reused the value of x will stay there.

Since it invokes UB, your attempt to read the contents of that memory can result in reading the right value, reading garbage, your programm crashing, or anything else.

0
ravi On

Returning address of local variable is undefined. Undefined means you can't predict whether it would output correct OR incorrect result. It's unfortunate that you got correct result.

0
Scott Hunter On

As you should not be accessing such "garbage" (a technical term), the system is free to deal with it as it sees fit. For example, there may have been other tasks whose completion would have affected correctly-written programs.

0
James Kanze On

When you return the address of a local variable, the resulting pointer "dangles"; accessing through a dangling pointer, or even just reading it, is undefined behavior. Which means that in theory, anything can happen. In practice, the compiled code won't return the memory of the local variables in the function to the OS; in most OS's, it couldn't even if it wanted to. So the memory just sits there, until someone else uses it. In the case of memory in a function, it will be reused when you call another function; until then, you will probably be able to access it and find the old values. Debugging builds might intentionally scribble over the memory on leaving the function, but the mainstream compilers don't do this. And of course, programs like valgrind might check that the pointer is valid, and log an error (but I don't know if valgrind actually catches this).