From 414acd49aba5647db777cb6010b5f2118acb6ef6 Mon Sep 17 00:00:00 2001 From: Cormac Relf Date: Mon, 6 Apr 2020 21:05:44 +1000 Subject: [PATCH 1/2] Add test to exercise mi_usable_size on aligned allocations --- test/test-api.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/test-api.c b/test/test-api.c index 166cfca6..e5827a93 100644 --- a/test/test-api.c +++ b/test/test-api.c @@ -152,6 +152,9 @@ int main() { } result = ok; }); + CHECK_BODY("malloc-aligned5", { + void* p = mi_malloc_aligned(4097,4096); size_t usable = mi_usable_size(p); result = usable >= 4097 && usable < 10000; mi_free(p); + }); CHECK_BODY("malloc-aligned-at1", { void* p = mi_malloc_aligned_at(48,32,0); result = (p != NULL && ((uintptr_t)(p) + 0) % 32 == 0); mi_free(p); }); From 0047b271f7aff49e49f205c3d609f41bf4061160 Mon Sep 17 00:00:00 2001 From: Cormac Relf Date: Mon, 6 Apr 2020 21:05:44 +1000 Subject: [PATCH 2/2] Call mi_page_usable_size_of with unaligned block rather than start of aligned memory --- src/alloc.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/alloc.c b/src/alloc.c index b1c4cd34..baa36225 100644 --- a/src/alloc.c +++ b/src/alloc.c @@ -472,15 +472,16 @@ size_t mi_usable_size(const void* p) mi_attr_noexcept { if (p==NULL) return 0; const mi_segment_t* const segment = _mi_ptr_segment(p); const mi_page_t* const page = _mi_segment_page_of(segment, p); - const mi_block_t* const block = (const mi_block_t*)p; - const size_t size = mi_page_usable_size_of(page, block); + const mi_block_t* block = (const mi_block_t*)p; if (mi_unlikely(mi_page_has_aligned(page))) { - ptrdiff_t const adjust = (uint8_t*)p - (uint8_t*)_mi_page_ptr_unalign(segment,page,p); + block = _mi_page_ptr_unalign(segment, page, p); + size_t size = mi_page_usable_size_of(page, block); + ptrdiff_t const adjust = (uint8_t*)p - (uint8_t*)block; mi_assert_internal(adjust >= 0 && (size_t)adjust <= size); return (size - adjust); } else { - return size; + return mi_page_usable_size_of(page, block); } }