[PATCH] malloc: add free_sized and free_aligned_sized from C23

Florian Weimer fweimer@redhat.com
Wed Jun 18 17:21:56 GMT 2025


* Justin King:

>  Should we exclude memalign etc. as well?
>
> The standard is quiet, as far as I know, on this since they do not
> exist in the standard. So that will be up to glibc, but we should keep
> in mind whatever glibc chooses very well may become the defacto
> standard on this. The sanitizers, which are being updated (by me) to
> support free_sized and free_aligned_sized, will enforce whatever we
> choose here.

Right.

> Perhaps we say that if the malloc-like function accepts explicit
> alignment (memalign/posix_memalign/aligned_alloc), it is undefined
> behavior to call free_sized. And permit those functions to call
> free_aligned_sized. And just say functions like valloc/pvalloc should
> not call free_sized, but may call free_aligned_sized so long as they
> replicate the documented size and alignment values. So for valloc
> free_aligned_sized must be called with sysconf(_SC_PAGESIZE) for
> alignment and original requested size; pvalloc free_aligned_sized must
> be called with sysconf(_SC_PAGESIZE) for alignment and the original
> requested size rounded up to a multiple of sysconf(_SC_PAGESIZE). We
> can mention that if you use valloc/pvalloc, we strongly recommend
> continuing to use free instead due to the subtlety.

Note that with valloc, callers would have to round up the allocation
size if used with free_aligned_sized.  I suggest not to go there at all.
We should perhaps allow posix_memalign in addition to aligned_alloc, but
that's it.

I realized that we probably have another gap: Can a pointer returned
from strdup and strndup be used with free_sized, and what should be size
to pass?  Is this aspect covered in the C23 standard?  If the language
is used is “as if by malloc”, this would be rather unfortunate because
it implies that free_sized can be used, somehow.  If it's been changed
to “suitable for passing to free and realloc”, we are good.

>From what I can see, we should not allow the use of any of these
secondary allocation functions.  (We also have asprintf, open_memstream,
realpath, and a couple more.)  The manual should be explicit about this.
And I just realized that we should also say that it is NOT possible to
recover the alignment and size from the pointer and via
malloc_usable_size.

Thanks,
Florian



More information about the Libc-alpha mailing list