Skip to content

support aligned allocation calls with alignments < pointer size #246

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/alloc-aligned.c
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@ terms of the MIT license. A copy of the license can be found in the file
// Aligned Allocation
// ------------------------------------------------------

static void* mi_heap_malloc_zero_aligned_at(mi_heap_t* const heap, const size_t size, const size_t alignment, const size_t offset, const bool zero) mi_attr_noexcept {
static void* mi_heap_malloc_zero_aligned_at(mi_heap_t* const heap, const size_t size, size_t alignment, const size_t offset, const bool zero) mi_attr_noexcept {
// note: we don't require `size > offset`, we just guarantee that
// the address at offset is aligned regardless of the allocated size.
mi_assert(alignment > 0 && alignment % sizeof(void*) == 0);

if (mi_unlikely(size > PTRDIFF_MAX)) return NULL; // we don't allocate more than PTRDIFF_MAX (see <https://sourceware.org/ml/libc-announce/2019/msg00001.html>)
if (mi_unlikely(alignment==0 || !_mi_is_power_of_two(alignment))) return NULL; // require power-of-two (see <https://en.cppreference.com/w/c/memory/aligned_alloc>)

// if the passed alignment is too small, correct it upwards to the minimal internal required alignment
// fixes issues in user code calling aligned variants for types with small alignment requirements below pointer alignment
alignment = alignment < sizeof(void*) ? sizeof(void*) : alignment;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be below the if()s below which check that we were fed with a non-0 power-of-two first, before alignment is changed. Those requirements are sane.

const uintptr_t align_mask = alignment-1; // for any x, `(x & align_mask) == (x % alignment)`

// try if there is a small block available with just the right alignment
Expand Down