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

HomePage Recent Changes Recently Commented Login/Register

Revision [758]

Most recent edit made on 2008-11-27 08:45:12 by SharathAV

Additions:

int *p; /* At this point, the pointer p is a wild pointer. */
/* Its uninitialized, so it may have any random address/value in it*/


Deletions:

int *p; /*At this point, the pointer p is a wild pointer. Its uninitialized, so it may have any random address in it*/




Revision [750]

Edited on 2008-10-21 11:06:02 by SharathAV

Additions:

CategoryPointers




Revision [361]

The oldest known version of this page was edited on 2007-05-31 07:47:56 by SharathAV

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 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
Valid XHTML 1.0 Transitional :: Valid CSS :: Powered by WikkaWiki
Page was generated in 0.0784 seconds