CS253: Software Development with C++

Spring 2019

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
2.7391e-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';

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2019-02-05T23:07

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building