CS253: Software Development with C++

Spring 2020

Dangling Pointers

Show Lecture.DanglingPointers as a slide show.

CS253 Dangling Pointers

Dangling Pointers

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

string *smith = new string("Brush your teeth after every meal!");
string *jones = smith;
delete smith;
cout << *jones << '\n';