Tuesday, March 13, 2012

Dangling Pointer?????????

pointers that do not point to a valid object of the appropriate type. Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. As the system may reallocate the previously freed memory to another process, if the original program then dereferences the (now) dangling pointer, unpredictable behavior may result, as the memory may now contain completely different data. This is especially the case if the program writes data to memory pointed by a dangling pointer, as silent corruption of unrelated data may result, leading to subtle bugs that can be extremely difficult to find, or cause segmentation faults (*NIX) or general protection faults (Windows). 


Let us understand through the following code snippet:-

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BLOCKSIZE 20;
int main()
{
char *ptr;
ptr=(char *)malloc(BLOCKSIZE);
if(ptr!=NULL)
strcpy(ptr,"mohin khan");
printf("content=%s",ptr);
printf("naddress=%u",ptr);
free(ptr);
printf("nAfter free");
printf("ncontent=%s",ptr);
printf("naddress=%u",ptr);
}
output of the above code
content=mohin khan
address=134520840      //(just a example)
After free
content=
address=134520840     //same as the previous address

so we can conclude from the above code that
after free() also i keeps the address but content is deallocated.so now it is not pointing to any valid memory location.Hence ptr is now dangling pointer which probably having a address but not pointing to any valid memory location.
so it is good practice to assign NULL after freeing the allocated memory as below

ptr=NULL;

in this way dangling problem will be solved. 




  <-------------------Thanking You----------------------> 

No comments:

Post a Comment

Please Give Me Your Views

Popular Posts