Search code examples
heap-memorymemory-alignmentcortex-meabi

ARM Cortex-M heap alignment


After being bitten by stack alignment problems I started wondering whether the heap should be aligned to 8-octet boundaries, as well.

The ARM Cortex EABI states that for all calls to external functions the stack has to be 8-aligned. I could not find any information on whether there are any restrictions to heap alignment. There seem to be some suggestions floating around stating that the heap should also be aligned by 8, but most publicly available memory management code aligns it by 4.

The stack alignment requirement should not have anything to do with the heap alignment (as long as word boundaries are honoured), as the alignment is not preserved when copying between heap and stack. Also, I cannot think of any reason why the compilers should be restricted to 8-aligned pointers when pointing to 8-octet-wide items.

Can anyone confirm that 4-octet alignment is sufficient for the heap?


Solution

  • For the specific case of Cortex-M processors, word-alignment is sufficient for heap allocations as there are no instructions on the Cortex-M that have a stricter alignment requirement than word-alignment.

    For the Cortex-M4 this is declared in the Cortex-M4 Devices Generic User Guide Section 3.3.5:

    An aligned access is an operation where a word-aligned address is used for a word, dual word, or multiple word access, or where a halfword-aligned address is used for a halfword access. Byte accesses are always aligned.

    That is, even for LDRD/STRD (dual word) and LDM/STM (multiple word access) instructions which are normally used by the compiler for 64bit data types, the requirement for an aligned access is only word-alignment.