What is Dangling Pointer in C language ?

As we know that, a pointer is a simple variable which holds the address of an another variable in a programs but, in this article we will going to discuss about what is dangling pointer in detail.

Dangling Pointer in C
Dangling Pointer

Dangling Pointer in C

Dangling Pointer in C is nothing but it also a type of pointer which indicates de-allocated memory space or points the non-existing memory location.

Example:

int main()
{
  int *ptr;
  ptr= (int*)malloc(sizeof(int));
  ......;
  ......;
  ......;
  free(ptr);
  return 0;
}

Here in this case 'ptr' contains the address of the first byte of the memory allocated by malloc( ), let me tell you that malloc( ) is the function that allocate the memory dynamically after allocating memory malloc( ) simply return the address of the first byte of the memory and that address I am try to store in this example in 'ptr'.

So 'ptr' contain the address the first byte of memory location after performing some operation, now what I am try do here is ? I want try to free the memory that is I am trying release the memory or I can say try to deallocate the memory by using 'free( )'  function.

After deallocating the memory by using free( ) function, but the pointer(ptr) still pointing to the deallocated memory is in that so.

Let us assume that address of the first byte of the memory is the one thousand(1000) 'ptr' still contain that address even after the deallocating the memory because we have reinitialized the pointer as simple as that after releasing the memory ptr still containing that address that is why 'ptr' is called the Dangling Pointer, it is because when we release or deallocate the memory after that pointer become dangling because it is pointing to the non existing memory location.

Example of Dangling Pointer

#include<stdio.h>
#include<conio.h>
int *fun()
{
  int num=10;
  return &num;
}
int main()
{
  int *ptr;
  ptr=NULL;
  ptr=fun();
  printf("%d",ptr);
  return 0;
}

_____________________________________________

Example of dangling pointer in c

_____________________________________________


1 Comments

Post a Comment
Previous Post Next Post