Sign up ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

The book "Data Structures in C" (Horowitz and Sahni) suggests that in the following code the pointer pf is behaving as a dangling reference:

float f,*pf;
pf=(float*) malloc(sizeof(float));
pf=(float*) malloc(sizeof(float));

The reasoning they give is that after the last line there is no way to retrieve the storage in which 2.6 was stored.

However, wikipedia defines a dangling pointer as

Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type

In the code above pf does not satisfy that definition - it points to a valid object of appropriate type.

Is pf a dangling pointer, or something else?

share|improve this question
do you have the ISBN for the book? there are several similarly titled books by the same authors – jk. May 23 '13 at 13:01
The example code given declares a regular float variable as well but it is not used - are you certain you've copied the example correctly? – Joris Timmermans May 23 '13 at 14:41

1 Answer 1

up vote 20 down vote accepted

No I wouldn't describe that as a dangling pointer, but it is a memory leak because you do not free the first malloc before the second malloc. A dangling pointer would typically be a pointer which points to something which e.g. has already been freed

float f,*pf;
pf = malloc(sizeof(float));
*pf = 2.6;
f = *pf; /*uhoh pf no longer points to valid memory */

Looking at the rest of code sample, f doesn't appear to be used, which is odd, and the cast to (float*) is unnecessary unless you need your code to also compile as C++ (something which was common when C++ was a newish language but not anymore, I suspect this may date your book?). While I can't find the exact book you reference, similar C and C++ books by the authors seem to have fairly poor reviews, you may want to consider a different textbook!

share|improve this answer
And, as the named wiki page says, pointer to variables that have fallen out of scope. – ott-- May 23 '13 at 11:57
yep that's another case. – jk. May 23 '13 at 12:06
@ott--: True, but then, I'd argue that a variable that has fallen out of scope has been freed: free is for freeing heap memory, automatic storage is for freeing stack memory. – ruakh May 23 '13 at 15:59
@jk,then the book is wrong to suggest that it is a dangling pointer – user1369975 May 23 '13 at 16:08
if that is what it says then yes. – jk. May 23 '13 at 16:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.