Home » Android » c++ – Memory alignment on iPhone and Android

c++ – Memory alignment on iPhone and Android

Posted by: admin June 15, 2020 Leave a comment


As I’ve discovered from my tests iPhone’s malloc has 16 byte alignment. But I’m not sure whether it is guaranteed or just coincidence.

So the question is: what is the guaranteed memory alignment when using malloc() on iOS and Android(NDK)?

How to&Answers:

malloc in C returns a pointer to a block of memory “which is suitably aligned for any kind of variable”; whether this alignment is or will remain at 16 bytes is not guaranteed even for different versions of the same OS. Objective-C is effectively based on C, so that should hold true there too.

If your Android NDK is written in C or C++, the same should hold true there.


On iOS, the alignment is currently 16 bytes, as you’ve discovered. However, that isn’t guaranteed, nor documented. I.e. don’t rely on it.

Assuming it is available on iOS, posix_memalign() allows for the allocation of specifically aligned memory. There may be other mechanisms.

Android is not my bailiwick.


I would agree that you still shouldn’t rely on this, but for something like a hash function it’s pretty helpful.

It is actually documented –


Allocating Small Memory Blocks Using Malloc

For small memory allocations, where small is anything less than a few virtual memory pages, malloc sub-allocates the requested amount of memory from a list (or “pool”) of free blocks of increasing size. Any small blocks you deallocate using the free routine are added back to the pool and reused on a “best fit” basis. The memory pool is itself is comprised of several virtual memory pages that are allocated using the vm_allocate routine and managed for you by the system.

When allocating any small blocks of memory, remember that the granularity for blocks allocated by the malloc library is 16 bytes. Thus, the smallest block of memory you can allocate is 16 bytes and any blocks larger than that are a multiple of 16. For example, if you call malloc and ask for 4 bytes, it returns a block whose size is 16 bytes; if you request 24 bytes, it returns a block whose size is 32 bytes. Because of this granularity, you should design your data structures carefully and try to make them multiples of 16 bytes whenever possible.