How do I make sure that memory accesses are properly aligned?
When running on the ARM processor it’s a good idea to make absolutely certain that all memory accesses are properly aligned. Accessing misaligned data as non-byte values will cause an exception unless the element is specifically identified as PACKED. This is normally caused by references to elements within byte arrays or streams as ints, etc. Alignment problems can arise when you improperly cast a pointer to a byte-sized item to a pointer to larger item (for example, to a structure, short or long). Generally, it is best to avoid such casts altogether. MALLOC() is one case where pointers must be cast, but MALLOC returns pointers that are properly aligned for any size. If you have any customized allocators, keep this in mind. Usually it’s a good idea to arrange the fields of a struct such that 32-bit fields come first, followed by 16-bit fields and then any 8-bit fields. This helps for both padding and alignment if one writes the struct into a file.