1

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?

iago-lito
  • 3,098
  • 3
  • 29
  • 54
  • 6
    It doesn't. It exhibits undefined behaviour. **Undefined** behaviour. If it appears to run fine, it's still not running fine. – chris Jul 26 '14 at 05:46
  • @chris: Okay, so the answer **is** "Super Lucky".. ;) – iago-lito Jul 26 '14 at 05:48
  • 1
    @chris Or rather, it might run fine in some places and under some circumstances with some compilers, and it might not in other cases, for some definition of "fine." – cdhowie Jul 26 '14 at 05:48
  • @Iago-lito, Super unlucky. And yeah, I guess if the compiler humours you and produces a valid program, you're in the clear until you change anything. – chris Jul 26 '14 at 05:50

1 Answers1

4

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.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • 1
    Fascinating. Cheers! ^ ^ – iago-lito Jul 26 '14 at 05:55
  • I understand the explanation, but why would the compiler let him reference a name that is not in scope? Surely that seems like a bad compiler. –  Jul 26 '14 at 06:21
  • 2
    @snowandotherjoys He never references a name that is not in scope. He stores a pointer to `d` in the `p` variable, then `d` goes out of scope, then he dereferences `p` to access the memory location where `d` used to be (but is no longer). – cdhowie Jul 26 '14 at 06:22