7

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=2.6;
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?

2
  • 1
    do you have the ISBN for the book? there are several similarly titled books by the same authors
    – jk.
    May 23, 2013 at 13:01
  • 2
    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? May 23, 2013 at 14:41

1 Answer 1

21

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;
free(pf);
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!

5
  • 2
    And, as the named wiki page says, pointer to variables that have fallen out of scope.
    – ott--
    May 23, 2013 at 11:57
  • yep that's another case.
    – jk.
    May 23, 2013 at 12:06
  • 1
    @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, 2013 at 15:59
  • @jk,then the book is wrong to suggest that it is a dangling pointer May 23, 2013 at 16:08
  • if that is what it says then yes.
    – jk.
    May 23, 2013 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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