Sunday, January 19, 2014

C Pointers - Dangling Pointer Problem

I found that many of under graduate students facing difficulties with pointers. In interviews generally the most of questions come from Pointers Only. Don't afraid of it . Make the basics clear by reading ANSI C or LET US C Or Try from some good video lectures. Here I am introducing some important aspects of pointers.



C pointers


Dangling Pointer Problem:

If any pointer is pointing to the memory address of a variable , but after sometime that variable is deleted from the memory. Now the pointer is still there and pointing to that particular location. Such pointer is known as dangling pointer and this problem is called dangling pointer problem.

So initially,

After the deletion of variable,
So now ptr is now become dangling pointer which is pointing to some garbage value.

Consider the following program:

#include<stdio.h>


int *foo();
void main(){

int *ptr;
ptr=foo();
printf("%d",*ptr);

}
int *foo(){

int x=25;
++x;

return &x;
}

Output of this programme:Garbage value
Here, Initially the pointer ptr is pointing the variable X of the function foo. The scope of X is only inside the function. So after returning address of X variable X became dead and pointer is still pointing ptr is still pointing to that location. 

The solution of this problem is , Make the variable X static so that it will not become dead or declare X as global variable then no such problem will arise.

You may Also like- Why C treats array parameters as pointers?


1 comment: