Search code examples
c++pointersmemory-managementscopememory-access

Why does this run fine ? (accessing address of an out-of-scope variable)


Why does this run fine? (And several times in a row..)

double* p(nullptr);
cout << p << endl;      // "00000000"
{
    double d(82.);
    p = &d;
}
cout << p << endl;      // "0029FD98"

// Naughty, dirty, sneaky..
// .. but rather *pure* curiosity after all.. u_u
cout << *p << endl;     // "82", first surprise
*p = 83.;               // (getting further down the hole..)
cout << *p << endl;     // "83", and I almost feel disappointed. :(

Isn't d supposed to be out of scope and 0029FD98 deallocated? Why isn't my OS mad at me? Am I just super lucky?


Solution

  • You are invoking undefined behavior. According to the C++ specification, anything might happen here. Undefined behavior is a very bad thing, because it means you cannot know what your program might do. Avoid it at all costs.

    On your particular platform with your particular compiler, this probably works because the variable was allocated on the stack, and the stack memory is not (usually) deallocated while the program is running. As a result, 0029FD98 refers to an address within an allocated region of memory (in this case, the stack). As soon as you call a function, this location is likely to be overwritten with whatever that function needs the stack space for.

    On other systems and/or compilers, where local variables and/or the stack might behave or be implemented differently, this could output some random number, or it might crash, or it might output the collective works of Shakespeare.