Aligning memory on iPhone and Android

As I learned from my tests, iPhone malloc has 16-byte alignment. But I'm not sure if this is guaranteed or just a match.

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

+7
source share
3 answers

malloc in C returns a pointer to a block of memory "that is properly aligned for any variable"; whether this alignment or remains at 16 bytes is not guaranteed even for different versions of the same OS. Objective-C is efficiently based on C, so it must remain true there.

If your Android NDK is written in C or C ++, then it should be true there.

+5
source

On iOS, alignment is currently 16 bytes, as you discovered. However, this is not guaranteed or documented. That is, do not rely on him.

Assuming it's available in iOS, posix_memalign() allows you to allocate specially aligned memory. There may be other mechanisms.

Android is not my bailiwick.

+6
source

I would agree that you still should not rely on this, but for something like a hash function, this is very useful.

Actually documented - https://developer.apple.com/library/ios/#documentation/performance/Conceptual/ManagingMemory/Articles/MemoryAlloc.html

Excerpts:

Allocating small memory blocks with Malloc

For small memory allocations, where small is something less than a few pages of virtual memory, malloc allocates the requested amount of memory from a list (or "pool") of free blocks of increasing size. Any small blocks that you free using a free routine are added back to the pool and reused according to the β€œbest fit” principle. The memory pool itself consists of several pages of virtual memory that are allocated using the vm_allocate procedure and are managed by your system.

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

+1
source

All Articles