What is dangling pointer?please explain with a suitable example!
1
Expert's answer
2011-07-06T08:51:57-0400
Dangling pointers are pointers that do not point to a valid object of theappropriate type, like you deleted what it points at. Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. As the system may reallocate the previously freed memory to another process, if the original program then dereferences the dangling pointer, unpredictable behavior may result, as the memory may now contain completely different data.
A straightforward example is shown below:
{ char *dp = NULL; /* ... */ { char c; dp = &c; } /* c falls out of scope */ /* dp is now a dangling pointer */ }
A solution to the above is to assign NULL to cp immediately before the inner block is exited. Another solution would be to somehow guarantee cp is not used again without further initialisation.
Comments
You are welcome!
Thank you very very much sir!!!
Leave a comment