+ 2

What is dangling pointer?

9th Oct 2019, 12:34 AM
Peetam Singh Dhangar
Peetam Singh Dhangar - avatar
2 Respostas
+ 5
The delete operator frees up the memory allocated for the variable, but does not delete the pointer itself, as the pointer is stored on the stack. Pointers that are left pointing to non-existent memory locations are called dangling pointers. // request memory int *p = new int; // store value *p = 5; // free up the memory delete p; // now p is a dangling pointer // reuse for a new address so pointer is no longer dangling p= new int; 📍 So bassically remember to not leave pointers, pointing to nothing when you free memory after use. In the lesson they suggest to reassign pointer to new location. 📍I think this important because memory is random access so eventually the dangling pointer would point to something completly wrong when that memory location becomes overwritten. Hope this helps I am still a beginner who just learnt this recently
9th Oct 2019, 1:38 AM
SpaceJam♨
SpaceJam♨ - avatar
+ 1
Adding on to what SpaceJam said, a common mistake people make is returning a local pointer/array int* f() { int a[] = {1,2,3}; return a; // a's lifetime ends at the end of this function scope, therefore the pointer returned is dangling }
9th Oct 2019, 2:55 AM
jtrh
jtrh - avatar