What Is a Dangling Pointer?


Ans: A pointer pointing to an object that has been destroyed is called a Dangling pointer. For example, the pointer ptr in the function given below is a dangling pointer.

main( )

{

int *ptr ;

int *f( ) ;

ptr = f( ) ;

printf ( “%d”, *ptr ) ;

}

int *f( )

{

int a = 10 ;

return ( &a ) ;

}

Here it appears that address of a would be collected in ptr and through *ptr we would be able to access 10. This however is not possible because by the time address of a is collected in ptr, a is already dead. So you have a pointer containing an address, and the object at this address is long dead. Thus ptr becomes dangling pointer.

Subscribe / Share

It's very calm over here, why not leave a comment?

Leave a Reply




Categories

Powered by Yahoo! Answers