Home / Tips / C Tips / C: What do you mean by a "dangling pointer"?

“Chishiki” is Japanese for “knowledge.” e-chishiki.com aims to bring software developers, information security professionals, IT executives and other IT pros a rich body of knowledge in the form of articles, interviews, tutorials and technical discussions. Our contributors are among the biggest names in the Indian IT industry and include noted authors, educators and practitioners.

C: What do you mean by a "dangling pointer"?


What do you mean by a "dangling pointer"?


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.

Comments

Log in or create a user account to comment.

On Sale From April 2008

Let Us C
8th Ed.
C programming classic & best seller. 1 million+ copies sold!

Y. Kanetkar

On Sale From April 2008

Introduction to Object Oriented Programming & C++

Y. Kanetkar

On Sale From Fall 2008

Microsoft .NET Framework: Web Application Security

Vijay Mukhi

On Sale From Nolvember 2008

Quest C++ Courseware
12+ hours of instructional audio and animated slides.

Y. Kanetkar Asang Dani

On Sale From November 2008

A Programmer's Guide to Web Application Security

Vijay Mukhi

Latest Forum Posts