Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to reference an out-of-scope local variable within the same function?

In this code, I reference the local variable b even though it is out of scope. But I do it from within the same function so it's probably still on the stack, right? I ran the program and it worked but I'd like to know if it's guaranteed to work on all implementations.

#include <iostream>

void main()
{
    int* a;
    {
        int b = 5;
        a = &b;
    }
    std::cout << *a;
}
like image 526
Petr Hudeček Avatar asked Jan 28 '14 20:01

Petr Hudeček


2 Answers

No, that's not guaranteed to work. a is dangling once the inner scope is exited, so any dereference of it results in Undefined Behaviour and nothing whatsoever is guaranteed.

like image 66
Angew is no longer proud of SO Avatar answered Sep 22 '22 03:09

Angew is no longer proud of SO


The problem here is not that b is out of scope. It is that the lifetime of b has ended. Scope is about where the name of an object is known. Lifetime is about when the object exists (within the computational model).

Technically, the object b does not exist when you reference it with *a. The bytes that were used to represent it might happen to be still unchanged in memory, and accessing them with *a might happen to work sometimes, especially if optimization is not turned on, but it is undefined behavior.

An object can still be accessible even though its name is not in scope. Here is an example of an object that is accessible during its lifetime even though it is not in scope:

void foo(void)
{
    int b;
    bar(&b);
}

In this code, the function bar may access b, even though it cannot see the name of b in foo. Although control leaves the block in which b is created, execution of the block is merely suspended, not terminated. So b continues to exist even while the function bar is executing. So b will be out of scope, but the access will be during its lifetime.

like image 33
Eric Postpischil Avatar answered Sep 22 '22 03:09

Eric Postpischil