aligned_alloc()

DJ Delorie dj@redhat.com
Fri Feb 24 01:03:05 GMT 2023


Re: https://sourceware.org/bugzilla/show_bug.cgi?id=20137
Re: https://patchwork.sourceware.org/project/glibc/patch/33ec9e0c1e587813b90e8aa771c2c8e6e379dd48.camel@posteo.net/

In reviewing this old discussion, I'll try to summarize...

#ifdef __USE_ISOC11
void *aligned_alloc (size_t alignment, size_t size);
#endif

glibc's implementation of this is a simple alias to memalign(), in
that it (1) accepts any alignment (up to SIZE_MAX), and (2) accepts
any size.  A non-power-of-two alignment is rounded up to a power of
two.

C11 requires that alignment be a power of two, and that size is a
multiple of alignment.

C17 drops the "size is a multiple of alignment" rule, allowing any
size.

The manual currently documents the C11 requirements.

There are two aspects of this - the code, and the manual.

The current code conforms to neither C11 nor C17, in that it does not
return NULL in cases where the standard requires it.  We can redo the
aligned_alloc symbol as a wrapper around _mid_memalign that checks for
these cases:

1. A check for alignment not power-of-two (C11/C17)

2. A check for size < alignment (C11)

3. A check for size % alignment (C11)

The current manual documents the C11 restrictions.  The PW patch
proposes to change this to document the C17 restrictions.  The options
are:

4. Change the manual to document glibc-as-is

5. Leave the manual as-is (C11)

6. Change the manual to document C17 (C17)

It has been noted that since we've always documented the C11
restrictions, changing the code to comply with those restrictions
should not require a versioned symbol.  However, if we strictly comply
with C11, we'd need a new symbol for C17.  Since those are wrapped by
__USE_ISOC* macros, we could (in theory) just #define aligned_alloc to
__aligned_alloc_c11 or __aligned_alloc_c17 for the modified versions.


So I propose we do this (ish):

#ifdef __USE_ISOC17
void *__aligned_alloc_c17 (size_t alignment, size_t size);
#define aligned_alloc(A,S) __aligned_alloc_c17 (A,S)
#else
#ifdef __USE_ISOC11
void *__aligned_alloc_c11 (size_t alignment, size_t size);
#define aligned_alloc(A,S) __aligned_alloc_c11 (A,S)
#endif
#endif

We would keep the existing aligned_alloc symbol as is.

The manual would be updated to match the new behavior.

Thoughts?



More information about the Libc-alpha mailing list