RFR: 8371637: allocateNativeInternal sometimes return incorrectly aligned memory

Jorn Vernee jvernee at openjdk.org
Tue Nov 11 16:27:07 UTC 2025


On Tue, 11 Nov 2025 14:11:28 GMT, Harald Eilertsen <haraldei at openjdk.org> wrote:

> `jdk.internal.foreign.SegmentFactories::allocateNativeInternal` assumes that the underlying implementation of malloc aligns allocations on 16 byte boundaries for 64 bit platforms, and 8 byte boundaries on 32 bit platforms. So for any allocation where the requested alignment is less than or equal to this default alignment it makes no adjustment.
> 
> However, this assumption does not hold for all allocators. Specifically jemallc, used by libc on FreeBSD will align small allocations on 8 or 4 byte boundaries, respectively. This causes allocateNativeInternal to sometimes return memory that is not properly aligned when the requested alignment is exactly 16 bytes.
> 
> To make sure we honour the requested alignment when it exaclty matches the quantum as defined by MAX_MALLOC_ALIGN, this patch ensures that we adjust the alignment also in this case.
> 
> This should make no difference for platforms where malloc allready aligns on the quantum, except for a few unnecessary trivial calculations.
> 
> This work was sponsored by: The FreeBSD Foundation

Thanks, I think I get it. What happens if you try to allocate 4 bytes of memory and request 8 byte alignment? Won't the result only be 4 byte aligned?

I think the assumption of the current optimization is wrong: that malloc always returns memory aligned to a _constant_ `MAX_MALLOC_ALIGN`, and instead it depends on the size of the allocation, and the underlying allocator. I think ideally we'd be able to ask the allocator what the alignment of the memory it will return of a certain size is (or ask it to do an aligned allocation). We could also use a helper method that returns the alignment for a certain allocation size:


private static final boolean IS_FREEBSD = System.getProperty("os.name").equals(...);

private long alignmentForSize(long size) {
    if (IS_FREEBSD) {
        ...
    } else {
        return Unsafe.ADDRESS_SIZE == 4 ? 8 : 16;
    }
}

-------------

PR Comment: https://git.openjdk.org/jdk/pull/28235#issuecomment-3517732223


More information about the core-libs-dev mailing list