Sunday 4 July 2010

Example program on Dangling pointer

What will be output of following c program?
//dangling pointer
#include<stdio.h>

void main()
{
int *ptr;
int *call();
ptr=call();
fflush(stdin);
printf("%d",*ptr);

}
int * call()
{
int x=25;
++x;
return( &x);
}

Output: Garbage value
Note: In some compiler you may get warning message returning address of local variable or temporary
Explanation: variable x is local variable. Its scope and lifetime is within the function call hence after returning address of x variable x became dead and pointer is still pointing ptr is still pointing to that location.
Solution of this problem:
Make the variable x is as static variable. In other word we can say a pointer whose pointing object has been deleted is called dangling pointer.
#include<stdio.h>

void main()
{
int *ptr;
int *call();
ptr=call();
fflush(stdin);
printf("%d",*ptr);

}
int * call()
{
static int x=25;
++x;
return &x;
}
Output: 26
You may like the following posts:
Pointers

No comments:

Post a Comment