Ferio
Ferio

Reputation: 516

C structure alignment

I’m trying to understand how structures are aligned. According to this source, I would have expected the struct

#include<inttypes.h>
#include<stdio.h>

typedef struct {
  uint16_t a;
  uint16_t b;
  uint32_t c;
} test_struct;

int main (int argc, char const *argv[])
{
  printf("%lu\n", sizeof(test_struct));
  return 0;
}

to have a size of 12 bytes. It only takes 8 bytes in my example. As it contains an 32 bit integer I thought it should be aligned to 4 bytes, apparently that isn’t the case.

After having looked around I found this this answer which suggests than only the members themselves need to be aligned.

This totally explains the size of my struct, but how does this line up with my first source claiming “a struct instance will have the alignment of its widest scalar member”? Is that wrong or am I missing something?

Upvotes: 0

Views: 1403

Answers (1)

Tyler
Tyler

Reputation: 750

Both of your sources are correct.

typedef struct {
uint16_t a; // 2 bytes
uint16_t b; // 2 bytes
uint32_t c; // 4 bytes
} test_struct;

The total size of the struct is 8 bytes. To determine if padding is needed, we examine the widest scalar member (4 bytes) and check if the that number is divisible by the total size without padding.

8 % 4 == 0

Thus we don't need padding.

If we had:

typedef struct {
uint16_t a; // 2 bytes
uint16_t b; // 2 bytes
uint32_t c; // 4 bytes
uint16_t d; // 2 bytes
} test_struct;

Total size: 10 bytes

12 % 4 == 2

Padding required: 2 bytes

Total actual size: 12 bytes

Upvotes: 2

Related Questions