14.21 – Wild pointer and Dangling pointer

by subbu on February 5, 2014

Wild Pointer

A pointer which is not initialized with any address is called wild pointer. The wild pointer is by default stored with the garbage value.

Be clear that there is difference among the NULL pointer and wild pointer. NULL pointer is assigned with the address 0 where as wild pointer is not assigned with any address.

#include<stdio.h>
int main()
{
 short *p;
 printf("%u",p);
 return 0;
}

Output:
818

Here p is the pointer pointing nothing, stored with the garbage value

Dangling pointer:

short *p;
p=(short*)malloc(2);

pointer to a variable

Here p points the memory allocation allocated by malloc().

free(p);

dangling pointer

Though we delete the allocated memory, p still points the same memory. If a pointer points de-allocated memory then the pointer is called dangling pointer.

 #include<stdio.h>
 int* test()
 {
   int a=10;
   return &a;
 }
 int main()
 {
   int *p;
   p=test();
 }

Here the scope of variable a of test() ends after returning the address to main(). Now p points a memory location which has de-allocated. So, here p is the dangling pointer.


#include<stdio.h>
int main()
{
 int *p;
 if(1)
 {
  int x=10;
  p=&x;
  printf("%d",*p);
 }
}

Here the scope of x ends once the control comes out of if conditional statement. Now p would be a dangling pointer as it is still pointing de-allocated memory.

Previous post:

Next post: