add is_aligned check

This commit is contained in:
Daan Leijen 2022-04-20 17:33:31 -07:00
parent d9f6ab58c5
commit 864e4be5ce
2 changed files with 9 additions and 1 deletions

View File

@ -217,6 +217,12 @@ static inline bool _mi_is_power_of_two(uintptr_t x) {
return ((x & (x - 1)) == 0); return ((x & (x - 1)) == 0);
} }
// Is a pointer aligned?
static inline bool _mi_is_aligned(void* p, size_t alignment) {
mi_assert_internal(alignment != 0);
return (((uintptr_t)p % alignment) == 0);
}
// Align upwards // Align upwards
static inline uintptr_t _mi_align_up(uintptr_t sz, size_t alignment) { static inline uintptr_t _mi_align_up(uintptr_t sz, size_t alignment) {
mi_assert_internal(alignment != 0); mi_assert_internal(alignment != 0);

View File

@ -633,7 +633,9 @@ void* _mi_heap_realloc_zero(mi_heap_t* heap, void* p, size_t newsize, bool zero)
memset((uint8_t*)newp + start, 0, newsize - start); memset((uint8_t*)newp + start, 0, newsize - start);
} }
if mi_likely(p != NULL) { if mi_likely(p != NULL) {
if mi_likely(_mi_is_aligned(p, sizeof(uintptr_t))) { // a client may pass in an arbitrary pointer `p`..
_mi_memcpy_aligned(newp, p, (newsize > size ? size : newsize)); _mi_memcpy_aligned(newp, p, (newsize > size ? size : newsize));
}
mi_free(p); // only free the original pointer if successful mi_free(p); // only free the original pointer if successful
} }
} }