Efficient C for ARM

Padding

Structures often end up containing padding.

Required because of target’s data type restrictions.
e.g. ARM keeps ints on a 32-bit boundary.

Easy to waste memory if you’re not aware of where padding is inserted.

Solution:

  • Sort elements in the structure by size:
    • Place elements in small-to-large or large-to-small order.
    • This minimises the amount of padding.

The compiler cannot perform this transformation itself as the C standard guarantees that structure members will be laid out in the order that they’re specified.

Examples

Consider the structure:

struct
{
  unsigned char type;
  int           product;
  short         delta;
}

It is laid out in memory like this:

Structure layout in memory - before.

If we sort the structure members by size:

struct
{
  int           product;
  short         delta;
  unsigned char type;
}

Structure layout in memory - before.

The padding can be removed and the structure reduces by four bytes (a third).

Navigate