Handwaving RFC: hypothetical recalloc() API
Florian Weimer
fweimer@redhat.com
Mon May 4 18:25:45 GMT 2026
* H. Peter Anvin:
> One thing that has bothered me for a very long time when implementing user
> space code is the realloc() + memset() anti-pattern.
There's been a closely related thread about functions proposed for C
standardization:
Request for feedback on WG14 proposal N3849 (alloc_at_least)
<https://inbox.sourceware.org/libc-alpha/CAHktk4jfh9qqipNs2V9_5fU7vK11_g-c_tUCafUG+yv7ZQL1CQ@mail.gmail.com/>
> All newly allocated memory, if any, is cleared. There is a potential hazard
> here: unless the existing malloc(), realloc() etc. functions are modified to
> always clear any spillover area (the difference between the buffer requested
> and the buffer allocated) then this would mean that the buffer size originally
> requested must be stored in the hidden buffer metadata. That clearing,
> however, might be desirable anyway for safety reasons (see above.)
We can do that in glibc malloc, but I think other allocators will be
really hard-pressed to do this, so they would have to clear the
potentially quite substantial tail unconditionally.
> I *really* dislike the posix_memalign() requirement that the alignment needs
> to be a multiple of sizeof(void *). It makes absolutely no sense; it is
> perfectly reasonable to specify any alignment down to single bytes,
> *especially* since even standard C now has an alignof() operator. For the
> allocator to not accept a value returned by alignof() is very serious brain
> damage. Furthermore, it is completely pointless: the allocator is obviously
> always permitted to return a larger alignment than requested.
Are there similar requirements for the newer aligned_alloc function?
> I would also suggest that an alignment of 0 would explicitly be defined as
> "the alignment of the largest type that can fit inside *n * size". Including
> *n in the calculation is because of the common-enough pattern with calloc() to
> always provide a byte count, regardless of the intended use of the buffer.
I think the C standard nowadays permits returning two-byte-alignment
memory for two-byte allocations. So I think this has been standardized,
except maybe for the symmetry in the calloc arguments.
Thanks,
Florian
More information about the Libc-alpha
mailing list