C / C++ FAQs & Programming Resources - ProkutFAQ : WildAndDanglingPointers

HomePage Recent Changes Recently Commented Login/Register
Quick Links
Categories
Links

What are wild and dangling pointers?

A pointer which is not initialized with any address is called as a wild pointer. It may contain any garbage address, so dereferencing a wild pointer is dangerous(as it causes undefined behavior). A dangling pointer is a pointer which no longer points to any valid location. It is just as dangerous as wild pointer as it contains invalid location.

Example:
#include<stdlib.h>
int main()
{
    int *p; /* At this point, the pointer p is a wild pointer. */
    /* Its uninitialized, so it may have any random address/value in it*/
    p=malloc(sizeof(int)*10); /* p is initialized with the address to an array of 10 integers */
    free(p); /* p becomes dangling pointer as it no longer points to a valid location. */
    p=NULL; /* p is no longer dangling pointer as it now initialized with NULL*/
}


To avoid the dangerous consequences that wild or dangling pointer may bring to the program, we should always initialize the pointer with NULL during declaration and immediately after the pointer is being freed.

References:

Wikipedia article on Wild and Dangling pointers


CategoryPointers
 Comments [Hide comments/form]
thank u
-- 210.212.230.129 (2009-07-29 12:10:17)
Page was generated in 0.0269 seconds