Re: To "const char *" and cast on free(), or "char *" and no cast...
From: Eric Wong <hidden>
Date: 2021-10-14 23:36:18
Ævar Arnfjörð Bjarmason [off-list ref] wrote:
On Thu, Oct 14 2021, Phillip Wood wrote: [Changed $subject]
Thanks, I might not've noticed this if you hadn't.
quoted
On 14/10/2021 01:10, Ævar Arnfjörð Bjarmason wrote:quoted
The "checkout" command is one of the main sources of leaks in the test suite, let's fix the common ones by not leaking from the "struct branch_info". Doing this is rather straightforward, albeit verbose, we need to xstrdup() constant strings going into the struct, and free() the ones we clobber as we go along.It's great to see these leaks being fixed. I wonder though if it would be better to change the structure definition so that 'name' and 'path' are no longer 'const'. That would be a better reflection of the new regime.[...]I think this is the right thing to do, but I'm not quite sure. There was a thread at it here: https://lore.kernel.org/git/YUZG0D5ayEWd7MLP@carlos-mbp.lan/ (local)
I'd much prefer we keep const-ness for safety and documentation purposes.
Where I chimed in and suggested exactly what you're saying here, but the
consensus seemed to go the other way, and if you grep:
git grep -F 'free((char *)'
You can see that we use this pattern pretty widely.
I've been using unions to workaround APIs like free(3)
for many years:
static inline void deconst_free(const void *ptr)
{
/* this initializer is a C99-ism */
union { const void *in; void *out; } deconst = { .in = ptr };
free(deconst.out);
}