c++ - How to check alignment of returned data in the malloc() implementation? -


malloc(sz) returns memory alignment works object.

on 32-bit x86 machines, means address value returned malloc()must evenly divisible 4. in practice, 32-bit malloc implementations return 8-byte aligned memory, meaning returned addresses evenly divisible 8. should too. (on x86-64/ia-64 machines, maximum data alignment 8, malloc implementations return 16-byte aligned memory.)

i have test situation

// check alignment of returned data.   int main()   {      double* ptr = (double*) malloc(sizeof(double));      assert((uintptr_t) ptr % __alignof__(double) == 0);      assert((uintptr_t) ptr % __alignof__(unsigned long long) == 0);       char* ptr2 = (char*) malloc(1);      assert((uintptr_t) ptr2 % __alignof__(double) == 0);      assert((uintptr_t) ptr2 % __alignof__(unsigned long long) == 0);   } 

my malloc code allocate more space user requested. first part of space used store metadata allocation, including allocated size.

sizeof(metadata) % 8 == 0

but heap

 static char heap[heap_capacity]; 

starting value not divided 8

metadata* block = (metadata*)heap; (uintptr_t)block % 8 != 0 

my tests fails, can in situation? how sure array begins address

metadata* block = (metadata*)heap; (uintptr_t)block % 8 == 0 

?

you use union force correct alignment (see union element alignment) or calculate starting index allocation correctly aligned (which reduce heap capacity 7 bytes).


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -