ADVANCED CONCEPT OF C -

DYNAMIC  MEMORY ALLOCATION(DMA)

  • The process of allocating memory during program execution is called dynamic memory allocation 
  • c language offers 4 dynamic memory allocation function. They are calloc(), malloc(),realloc(),free()
  • stdlib.h 

Dangling pointer in c

  • Dangling Pointer occurs when a pointer pointing to a variable goes out of scope or when an object/variable's memory gets deallocated,
  • Dangling pointers arise when an object is deleted or de-allocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the de-allocated memory.
  • In short pointer pointing to non-existing memory location is called dangling pointer.
  • There are three different ways in which a pointer can act as a dangling pointer in C :
  1. Deallocation of memory
  2. Function Call 
  3. Variable goes out of scope


ADVANCED C
  1. Deallocation of memory

When we deallocate a memory block using free() function and do not modify the pointer value, it will cause the pointer to act as a Dangling Pointer.

// Dangling Pointers using dynamic memory allocation 

 #include 

 #include 

int main() 

 {

 int *ptr = (int *)malloc(sizeof(int)); // normal pointer 


 *ptr = 10;

 // memory block deallocated using free() function free(ptr); 

 // here ptr acts as a dangling pointer 

 printf("%d", *ptr);

 // prints garbage value in the output console 

return 0;

 }  

kaushal katira

My self kaushal katira i am student of it. i live in rajkot gujarat

Post a Comment

Previous Post Next Post