Skip to content

mi_malloc_aligned does not return aligned pointers for small-sized allocations #206

@licheng

Description

@licheng

Hi,

After the upgrade to version 1.6.0, mi_malloc_aligned does not always return aligned pointers for small-sized allocations.

Here is a program for test:

#include <stdio.h>
#include "mimalloc.h"

int main() {
        int i;
        for (i = 0; i < 4; i++) {
                void* ptr = mi_malloc_aligned(8, 16);
                printf("%p %d\n", ptr, (size_t)ptr % 16);
        }
        return 0;
}

Output:

0x53bda001100 0
0x53bda001108 8
0x53bda001110 0
0x53bda001118 8

I expect all pointers are aligned by 16-bytes, but some of them are 8-bytes aligned.

After some debugging, I found the problem may be caused by commit 4531367 :

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 {
  // 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 (alignment <= MI_MAX_ALIGN_SIZE && offset==0) return _mi_heap_malloc_zero(heap, size, zero);

If alignment <= 16 bytes, the function _mi_heap_malloc_zero is called without alignment requirement. But It seems _mi_heap_malloc_zero does not always return a pointer aligned by MI_MAX_ALIGN_SIZE.

I'm not sure if I understand correctly. Is this a bug?

Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions