C Language - Dangling Pointer

 



#include <stdio.h>

#include <stdlib.h>

#include <conio.h>

extern int b=23;

int *dangfunc ()

{

int a,b,c;

a=34;

b=343;

c= a*b;

printf ("The value of c is %d\n", c);

return &c;

}


int main()

{

// THERE ARE THREE CASES OF DANGLING POINTERS:-

// Case1: Deallocation of a memory block.

int*ptr = (int*) malloc (5*sizeof (int));

ptr[0] = 343;

ptr[1] = 543;

ptr[2] = 642;

ptr[3] = 3434;

ptr[4] = 233;

printf ("The pointer ptr is %d\n", ptr);

free(ptr); 

// (ptr is now dangling pointer)

printf ("the value of b is %d\n", b);

// Case2: function returning local variable.

int *shan = dangfunc(); 

//dangfunc() is now a dangling pointer.


//Case3: if a variable goes out of scope.

int *dangptr3;

{

int a=343;  

dangptr3=&a;  

printf ("the value of a is %d\n", *dangptr3);

}  

// Now, the variable 'a' goes out of scope. so, the dangptr3 become now a dangling ptr.

return 0; 

 


// ScreenShots:






Comments

Popular Posts