In this tutorial, you are going to learn about Dangling Pointer and Wild Pointer in C.
Dangling Pointer
A Dangling Pointer is a pointer which points to some non existing memory location.
Example:
#include <stdio.h>
int* fun()
{
int num=10;
return #
}
int main()
{
int *ptr= NULL;
ptr= fun();
printf("%d", *ptr);
return 0;
}
Wild Pointer
Wild Pointers are also known as uninitialized pointers. These pointers usually point to some arbitrary memory location and may cause a program to crash or misbehave.
Example:
int main()
{
int *p; //This a wild pointer.
*p = 10;
return 0;
}
How to Avoid Wild Pointers
1. Initialize them with the address of a known variable.
Example:
int main()
{
int var= 10;
int *p;
p= &var; //No more a wild pointer.
return 0;
}
2. Explicitly allocate the memory and put the values in the values in the allocated memory.
Example:
int main()
{
int *p= (int *)malloc(sizeof(int));
*p= 10;
free(p);
return 0;
}
This article on Dangling Pointer and Wild Pointer in C is contributed by Rajnish Kumar. If you like TheCode11, then do follow us on Facebook, Twitter and Instagram.