Dangling Pointer - Cause of Dangling Pointers

Cause of Dangling Pointers

In many languages (e.g., the C programming language) deleting an object from memory explicitly or by destroying the stack frame on return does not alter associated pointers. The pointer still points to the same location in memory even though the reference has since been deleted and may now be used for other purposes.

A straightforward example is shown below:

{ char *dp = NULL; /* ... */ { char c; dp = &c; } /* c falls out of scope */ /* dp is now a dangling pointer */ }

If the operating system is able to detect run-time references to null pointers, a solution to the above is to assign 0 (null) to dp immediately before the inner block is exited. Another solution would be to somehow guarantee dp is not used again without further initialization.

Another frequent source of dangling pointers is a jumbled combination of malloc and free library calls: a pointer becomes dangling when the block of memory it points to is freed. As with the previous example one way to avoid this is to make sure to reset the pointer to null after freeing its reference—as demonstrated below.

#include void func { char *dp = malloc(A_CONST); /* ... */ free(dp); /* dp now becomes a dangling pointer */ dp = NULL; /* dp is no longer dangling */ /* ... */ }

An all too common misstep is returning addresses of a stack-allocated local variable: once a called function returns, the space for these variables gets deallocated and technically they have "garbage values".

int *func(void) { int num = 1234; /* ... */ return # }

Attempts to read from the pointer may still return the correct value (1234) for a while after calling func, but any functions called thereafter will overwrite the stack storage allocated for num with other values and the pointer would no longer work correctly. If a pointer to num must be returned, num must have scope beyond the function—it might be declared as static.

Read more about this topic:  Dangling Pointer

Famous quotes containing the word dangling:

    And, indeed, is there not something holy about a great kitchen?... The scoured gleam of row upon row of metal vessels dangling from hooks or reposing on their shelves till needed with the air of so many chalices waiting for the celebration of the sacrament of food. And the range like an altar, yes, before which my mother bowed in perpetual homage, a fringe of sweat upon her upper lip and the fire glowing in her cheeks.
    Angela Carter (1940–1992)