Saturday 12 March 2016

In C, why do some people cast the pointer before freeing it?



I'm working on an old code base and pretty much every invocation of free() uses a cast on its argument. For example,



free((float *)velocity);
free((float *)acceleration);
free((char *)label);



where each pointer is of the corresponding (and matching) type. I see no point in doing this at all. It's very old code, so I'm left wondering if it's a K&R thing. If so, I actually wish to support the old compilers that may have required this, so I don't want to remove them.



Is there a technical reason to use these casts? I don't even see much of a pragmatic reason to use them. What's the point of reminding ourselves of the data type right before freeing it?



EDIT: This question is not a duplicate of the other question. The other question is a special case of this question, which I think is obvious if the close voters would read all the answers.



Colophon: I'm giving the "const answer" the checkmark because it is a bonafide real reason why this might need to be done; however, the answer about it being a pre-ANSI C custom (at least among some programmers) seems to be the reason it was used in my case. Lots of good points by many people here. Thank you for your contributions.


Answer




Casting may be required to resolve compiler warnings if the pointers are const. Here is an example of code that causes a warning without casting the argument of free:



const float* velocity = malloc(2*sizeof(float));
free(velocity);


And the compiler (gcc 4.8.3) says:



main.c: In function ‘main’:
main.c:9:5: warning: passing argument 1 of ‘free’ discards ‘const’ qualifier from pointer target type [enabled by default]

free(velocity);
^
In file included from main.c:2:0:
/usr/include/stdlib.h:482:13: note: expected ‘void *’ but argument is of type ‘const float *’
extern void free (void *__ptr) __THROW;


If you use free((float*) velocity); the compiler stops complaining.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...