Show Lecture.DanglingPointers as a slide show.
CS253 Dangling Pointers
Dangling Pointers
- After
delete
is called on a pointer, its value (address) is, theoretically,
indeterminate.
Accessing the value invokes undefined behavior. ☠
- In many implementations, the address is simply left unchanged.
- After a pointer is deleted, the pointer is “stale” or “dangling”.
Even though you still have a pointer to the data, you’re not
allowed to access the data.
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
4.04096e-320
56.78
Another way
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;
}
␀␀
No Reference Counting
- C++ has no garbage collection, and so has no built-in reference counting.
- This is bad code. Bad!
string *smith = new string("Brush your teeth after every meal!");
string *jones = smith;
delete smith;
cout << *jones << '\n';