tushars
tushars

Reputation: 53

Why c struct padding is required at __last__ element

I am aware of padding, and its rules, why it requires etc.

My question is given struct,

struct my_struct {
   int a;
   char c;
};

In this case start address of c is word align, but still compiler added 3 bytes (assuming 4 as word size) padding. with no element after c and why we need these 3 bytes? I checked following,

int g_int1;
struct my_struct st;
int g_int2;

by above what I mean is my rest of variable declarations are not dependent on word align-ness of previous variable size. compiler always try to align next variable irrespective of its global or local auto var.

I cant see any reason with endian-ness since this is char and for one byte it don't matters. what reason I think is instead of checking last element condition compiler always add padding whenever required.

what can the valid reason?

Upvotes: 3

Views: 1457

Answers (3)

junix
junix

Reputation: 3211

It's to have the object size also aligned. Imagine having an array of my_structs. In this case you need to align the start adress of every element. Therefore sizeof(struct my_struct) must be "aligned". Otherwise you are not able to tell how much memory you need to allocate.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272637

Because if sizeof(my_struct) was 5 rather than 8, then if you did this:

my_struct array[2];

then array[0] would be word-aligned, but array[1] would not be. (Recall that array lookup is done by adding multiples of sizeof(array[0]) to the address of the first element.)

Upvotes: 12

Alexey Frunze
Alexey Frunze

Reputation: 62086

Imagine you have an array of struct my_struct. How would its elements be word-aligned if they aren't a multiple of words in size each?

Upvotes: 6

Related Questions