C Pointers – Is This a Valid Example of a Dangling Pointer?

cpointers

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?

Best Answer

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!

Related Topic