1

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?

trincot
  • 317,000
  • 35
  • 244
  • 286
DrV
  • 22,637
  • 7
  • 60
  • 72

1 Answers1

1

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.

  • From this answer I don't understand why should Heap be aligned to 8 bytes. Since **word-aligned address is used for a word, dual word, or multiple word access**, it is enough to align to 4 bytes. Why they use 8 bytes alignment? As by me this post is not an answer. – kyb Jul 07 '17 at 11:12
  • The original question and my answer are specific to Cortex-M, where 4 byte alignment is sufficient for any use because the processor core itself never requires stricter alignment for any accesses. There are other processor core architectures where it is necessary with stricter alignment to facilitate correct access to all possible types that the code may use in the allocated memory. Therefore you may encounter heap implementations that have stricter alignment. – thomasthorsen Jul 08 '17 at 14:35