Using Dangling Pointers

A “dangling pointer” is one that points to a memory area no longer in use by your program. Dangling pointers, like uninitialized pointers, can be very dangerous to use.

For instance, say you allocate a block of memory with the malloc library function:

#define BUFSIZE 1000

char *ptr;

if( ptr = (char *) malloc( BUFSIZE ) )

/* do something */ ;

After the memory block has been allocated with malloc, the pointer ptr points to a valid data object. Once you're done using allocated memory, you normally return it to the heap:

free( ptr );

After you free the memory it points to, ptr is a dangling pointer. It still points to a valid machine address, but that address is no longer in use by the program. You shouldn't use the pointer at this stage, just as you shouldn't use it before it has been initialized.

Dangling pointers can also be created by a function that returns a pointer to a local variable:

int *boo_boo( void )

{

int object;

.

.

.

return &object; /* Error! */

}

The boo_boo function returns the address of the local variable object, forgetting the storage for object is no longer part of the program after the function ends.

Here's a variant of the previous example involving a string pointer:

char *boo_boo( void )

{

char *c_ptr;

c_ptr = "Hello";

.

.

.

return c_ptr; /* Error! */

}

Since the string constant "Hello" is local to the function, it evaporates when the function ends, leaving the pointer c_ptr dangling.