A million dollar question

Started by
8 comments, last by MaulingMonkey 18 years, 10 months ago
I'm trying to understand how struc/memebrs alignment work if the compiler assumes the objects of the same structure is the same. lets say struct S { char a; int b; } ; S s1; .... ... S s2; now S objects will be aligned on 1 byte boundaries and b is on 4 bytes boundaries then it will not be true for all cases of s1 and s2 assume s1 is on address 0 0 a 1 2 3 4 b 3 bytes padding for b but if s2 is on address 6 6 a 7 8 9 10 b then b is not on 4 byte boundaries how is that? how the alignment rules guarantees correct boundaries?
Advertisement
The alignment rules are based on the assumption that the structure will be on a compatible boundary. This would be true if you allocate a single instance or an array of the class, as the allocation function will ensure the boundary is correct (usually by allocating on a 16-byte boundary). As long as that assumption holds true for the first object in an array, the alignment rules guarantee it will be true for all other objects in that array.
For 4-byte alignment:

byte 0 is s1.a
bytes 1, 2, and 3 will be padding bytes.
bytes 4, 5, 6, and 7 are s1.b
sizeof(s1) = 8 bytes.

byte 8 is s2.a
bytes 9, 10, and 11 will be padding bytes.
bytes 12, 13, 14, and 15 are s2.b
sizeof(s2) = 8 bytes.

Is there anything with that, that you don't understand?
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
It's that you who don't undersantd my question.
what about the case I gave in the example? I'm not talking about arrays.
Because the structure "S" contains an object which requires 4-byte alignment, the struct itself requires 4-byte alignment (a struct will inherit the alignment of the member with the largest alignment).

This means that it simply would not be placed on address 6 in the first place.
Catafriggm answered your problem.

S objects will NOT be aligned on 1 byte boundries, it will most likely be on either a 4, 8, or 16 byte boundry, therefore s2 can never be at address 6. Inner-structure padding ensures that the variable will line up when the entire structure is lined up.

Edit: Buuuu, AR beat me to the punch [lol]
and what's the best reference/manual to check this out?

it's not mentioned in the c specification manual i guess.

thanks.
what if I specify the alignment for one member to be non power of two?
don't know the answer? ok don't worry.
Chatroom, this is not! Patience, young grasshoppa!!! :-).

Alignment specifics are compiler specific. Are you talking about, for example, setting the alignment of b to 1? That'd result in:

        +---------+0x0000  | char a  |        +---------+0x0001  | int b   |        |-   .   -|0x0002  |    .    |        |-   .   -|0x0003  |    .    |        |-   .   -|0x0004  |    .    |        +---------+


b would simply be aligned to a 1 byte boundry...

This topic is closed to new replies.

Advertisement