Sujet : Re: So You Think You Can Const?
De : tr.17687 (at) *nospam* z991.linuxsc.com (Tim Rentsch)
Groupes : comp.lang.cDate : 08. Jan 2025, 21:24:47
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <86bjwh835c.fsf@linuxsc.com>
References : 1 2
User-Agent : Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Andrey Tarasevich <
andreytarasevich@hotmail.com> writes:
On 01/07/25 11:32 AM, Julio Di Egidio wrote:
>
Assuming, as said, that the data was originally
allocated with malloc, is [calling free on a pointer
to const something] safe or something can go wrong
even in that case?
>
It is perfectly safe. One can even argue that standard declaration if
free` as `void free(void *)` is defective. It should have been `void
free(const void *)` from the very beginning.
I think declaring the parameter as 'void *' rather than 'const void *'
is a better choice. There is a fair chance that calling free() on a
pointer to const anything is a programming error, and it would be good
to catch that. If it isn't an error, then fixing the diagnostic is
trivial. If it's a common pattern one could even define an inline
function
static inline void
cfree( const void *p ){ free( (void*)p ); }
and call that instead of free(). (Obviously the 'inline' should be
taken out if compiling as C90.)