Show Lecture.DanglingPointers as a slide show.
delete
is called on a pointer, its value (address) is, theoretically,
indeterminate.
Accessing the value invokes undefined behavior. ☠
double *laurel = new double(12.34); cout << *laurel << '\n'; // should be 12.34 delete laurel; cout << *laurel << '\n'; // value is unknown double *hardy = new double; // will probably re-use space hardy[0] = 56.78; cout << *laurel << '\n'; // most likely 56.78 for LAUREL
12.34 2.7391e-320 56.78
Don’t return a pointer to something that will soon go away.
// Return a cheery message: const char *message() { char buf[] = "Hello there, folks!\n"; const char *p = buf; return p; } int main() { cout << message(); // Why doesn’t this work!? return 0; }
␀␀
string *smith = new string("Brush your teeth after every meal!"); string *jones = smith; delete smith; cout << *jones << '\n';