bug-gnulib
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: new module 'aligned-malloc'


From: Jeffrey Walton
Subject: Re: new module 'aligned-malloc'
Date: Tue, 21 Jul 2020 05:25:27 -0400

On Tue, Jul 21, 2020 at 4:48 AM Bruno Haible <bruno@clisp.org> wrote:
>
> In new gnulib code, I need to allocate memory blocks through malloc() but with
> a 16-bytes alignment.
>
> The posix_memalign and memalign functions only help on those platforms where
> they exist. It's not possible to emulate posix_memalign or memalign when they
> are not present, because when malloc() returned p, we can call free (p)
> but not free (p+4) or free (p+8) or similar.
>
> Gnulib has a module 'pagealign_alloc' but it produces a getpagesize() 
> alignment
> - not useful (very wasteful) for a 16-bytes alignment.
>
> So here is a module that provides aligned_malloc() and aligned_free().
>
> The alignment is given at compile-time, so that when the desired alignment is
> <= the alignment guaranteed by malloc(), there is no overhead. (With an
> alignment given at runtime, the aligned_free() function would have to fetch
> a back-pointer in all cases, and that means wasting sizeof (void *) bytes
> in the case where the desired alignment is small.)
>
>
> 2020-07-21  Bruno Haible  <bruno@clisp.org>
>
>         aligned-malloc: Add tests.
>         * tests/test-aligned-malloc.c: New file.
>         * modules/aligned-malloc-tests: New file.
>
>         aligned-malloc: New module.
>         * lib/aligned-malloc.h: New file.
>         * m4/malloc-align.m4: New file.
>         * modules/aligned-malloc: New file.
>         * doc/posix-functions/posix_memalign.texi: Mention the new module.
>         * doc/glibc-functions/memalign.texi: Likewise.

Hi Bruno,

Checkout  https://forum.kde.org/viewtopic.php?p=66274 for some info on
detection of posix_memalign. That one bit me several years ago.

I think there's also another option, if interested. On x86 you can get
aligned allocations with _mm_malloc. And with PPC you can get an
aligned block with vec_malloc.

As you probably know, Linux aligns heap allocations to 16 by default.
If you want to test the code path where you are stashing away the
offset at ptr[-1], do so on AIX. AIX aligns to 4 bytes by default
(iirc).

Jeff



reply via email to

[Prev in Thread] Current Thread [Next in Thread]