What is dangling pointer?

Share on FacebookTweet about this on TwitterDigg thisPin on PinterestShare on LinkedInShare on StumbleUponShare on TumblrShare on Google+Email this to someone

Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type.

In many applications memory is allocated for holding data objects. After using these objects, tha aplication will de-allocate this memory so that the memory can be re-used. In some cases the alications may use a pointer to an object whose memory is already de-allocated. This may lead to application crash or an unpredictable behavior.

scenarios which leads to dangling pointer

  1. Application makes use of a object after it has been released, and there by access to an invalid memory location.
  2. A function returns a pointer to one of its local variables, and since this local variable is defined only fro the function, the pointer becomes invalid once the function ends.

The most common result of this bug is the crash of the application or its running thread.

Examle 1:

1
2
3
4
5
6
7
8
9
#include "stdlib.h"
 
void func()
{
    char *dp = malloc(A_CONST);
    /* ... */
    free(dp);         /* dp now becomes a dangling pointer */
    /* ... */
}

Example 2:

1
2
3
4
5
6
7
8
9
{
   char *dp = NULL;
   /* ... */
   {
       char c;
       dp = &c;
   } /* c falls out of scope */
     /* dp is now a dangling pointer */
}

Example 3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "stdio.h"
 
int *call();
void main(){
 
int *ptr;
ptr=call();
 
fflush(stdin);
printf("%d",*ptr);
}
 
int * call(){
 
int x=25;
++x;
 
return &x;
}

Share on FacebookTweet about this on TwitterDigg thisPin on PinterestShare on LinkedInShare on StumbleUponShare on TumblrShare on Google+Email this to someone

Leave a Reply