c - What guarantees about low order bits does malloc provide? -
c - What guarantees about low order bits does malloc provide? -
when phone call c's malloc, there guarantee first few low order bits be? if you're writing compiler/interpreter dynamic language want have fixnums of form bbbbbbbb bbbbbbbb . . . bbbbbbb1 (where b bit) , pointers of form bbbbbbbb bbbbbbbb . . . bbbbbbb0 (or vice versa), there way guarantee malloc homecoming pointers fit such scheme?
should allocate 2 more bytes need, increment homecoming value 1 if necessary fit bit scheme, , store actual pointer returned malloc in sec byte know free?
can assume malloc homecoming pointer 0 final bit? can assume x86 have 2 0 bits @ end , x64 have 4 0 bits @ end?
c doesn't guarantee low order bits beingness 0 pointer aligned perchance types. in practice 2 or 3 of lowest bits zero, not count on it.
you can ensure yourself, improve way utilize posix_memalign.
if want need overallocate memory , maintain track of original pointer. (assuming want 16-byte alignment, made generic, not tested):
void* my_aligned_malloc16(size_t sz) { void* p = malloc(sz + 15 + 16); // 15 ensure alignment, 16 payload if (!p) homecoming null; size_t aligned_addr = ((size_t)p + 15) & (~15); void* aligned_ptr = (void*) aligned_addr; memcpy(aligned_ptr, &p, sizeof(void*)); // save original pointer payload homecoming (void*)(aligned_addr + 16); // homecoming aligned address past payload } void my_aligned_free16(void* ptr){ void** original_pointer = (void**)( ((size_t)ptr) - 16 ); free(*original_pointer); }as can see rather ugly, prefer using posix_memalign. runtime has similar function if 1 unavailable, e.g. memalign (thanks @r..) or _aligned_malloc when using msvc.
c malloc
Comments
Post a Comment