What is dangling pointer

Questions by vijaymca

Showing Answers 1 - 4 of 4 Answers

sjappasab

  • Jun 25th, 2008
 

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.

  Was this answer useful?  Yes

ishwar

  • Oct 18th, 2011
 

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.

  Was this answer useful?  Yes

SURESH KUMAR KOLLIMALLA

  • May 10th, 2013
 

By using dangling pointer we can access the values at the deallocated memory here, in the below code the memory allocated for variable n will be dealloeated as and when the control transfers from function hi() to main() but with the help of DPtr we can access the value of n.

Code
  1.  void main ( )

  2. {  

  3.    int *DPtr;          

  4.    DPtr=hi();    

  5.    printf(%d,DPtr);      

  6.  

  7. }  

  8.  

  9. int* hi( )

  10.  

  11. {      

  12.     int n = 5;

  13.     return &n; }

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions