Posts Tagged ‘memory’

Structures and Memory Consumption in C

Motivation

The way you design you structures in C can have a (significant) impact on the size they occupy in memory!

Memory structure of a structure

A structure occupies contiguous space in memory. Though, in order to provide efficient access to the structure’s fields, C uses padding. In other words, the fields are aligned to the memory words.

Example

In a system with:

  • word : 4 bytes
  • char : 1 byte
  • int : 4 bytes

without padding would be:

char (8bit) int (32bit)

and since the word size is 4 bytes the integer would belong to 2 different words, so in order to access it, two memory accesses would be necessary.
In order to avoid it, the actual memory organization is:

char (8bit) padding (24bit) int (32bit)

The Possible Problem

A bad designed structure can possible occupy more space than needed.

Example

Take a look at the following structure:

struct bad {
  char c1;
  int i1;
  char c2;
};

One would possibly say that since 1 + 4 + 1 = 6 bytes is the total size of the fields, 2 words = 8 bytes will be needed to store it. This is not true. Due to the padding we have:

c1 (8bit) padding (24bit) i1 (32bit) c2 (8bit) padding (24bit)

3 words = 12 bytes, 4 more bytes than necessary.

Solution

Just take into account how the types fit together:

struct good {
  char c1; //c1 + c2 = 2 bytes
  char c2;
  int i1;
};

This design needs the minimum number of 2 words = 8 bytes.

Outcome

The bigger the structure gets, the more space you can lose.. So, take care of it while designing the structures!