What are Wild Pointers? How can we avoid?

Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave badly.

filter_none

edit
close

play_arrow

link
brightness_4
code

int main()
{
  int *p;  /* wild pointer */
   /* Some unknown memory location is being corrupted. 
   This should never be done. */ 
  *p = 12; 
}

chevron_right


Please note that if a pointer p points to a known variable then it’s not a wild pointer. In the below program, p is a wild pointer till this points to a.

filter_none

edit
close

play_arrow

link
brightness_4
code

int main()
{
  int  *p; /* wild pointer */
  int a = 10;
  p = &a;  /* p is not a wild pointer now*/
  *p = 12; /* This is fine. Value of a is changed */ 
}

chevron_right


If we want pointer to a value (or set of values) without having a variable for the value, we should explicitly allocate memory and put the value in allocated memory.

filter_none

edit
close

play_arrow

link
brightness_4
code

int main()
{
   int *p = (int *)malloc(sizeof(int));
  *p = 12; /* This is fine (assuming malloc doesn't return NULL) */ 
}

chevron_right




My Personal Notes arrow_drop_up

Improved By : vishnureddy7



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.