What is Dangling pointer?

C Programming Language >   Pointer in C Language >   Pointer Expressions and Arithmetic  

Long Question

3992


Answer:

Dangling Pointer is a pointer that doesn’t point to a valid memory location. 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. Following are examples.

// EXAMPLE 1
int *ptr = (int *)malloc(sizeof(int));
.............
.............
free(ptr); 
 
// ptr is a dangling pointer now and operations like following are invalid
*ptr = 10;  // or printf("%d", *ptr);
Run on IDE

// EXAMPLE 2
int *ptr = NULL
{
   int x  = 10;
   ptr = &x;
}
// x goes out of scope and memory allocated to x is free now.
// So ptr is a dangling pointer now.


This Particular section is dedicated to Question & Answer only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.