-1

Consider the following piece of code

#include <iostream>

typedef struct A
{
    uint32_t var1;
    uint32_t var2;
    uint32_t var3;
    uint32_t var4;
    uint32_t var5;
} A_t;
typedef struct B
{
    uint32_t var1;
    uint32_t var2;
    uint32_t var3;
    uint64_t var5;
} B_t;

int main(){
    std::cout << "Size of A: " << sizeof(A_t) << std::endl;
    std::cout << "Size of B: " << sizeof(B_t) << std::endl; 

}

Compiling this normally with gcc gives the following output

Size of A: 20
Size of B: 24

Compiling this with the -m32 flag gives this output:

Size of A: 20
Size of B: 20

Is there a difference in the way padding is done when compiling in 32bit vs 64 bits? I am on x86_64-apple-darwin17.3.0 running gcc

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Iliketoproveit
  • 445
  • 6
  • 15
  • It looks like it unless for some strange reason the size of `uint64_t` changes between having and not having the `-m32` compiler flag – Daniel Mar 07 '18 at 23:56
  • 3
    alignment requirement might change between 32/64 (in particular `uint64_t`). – Jarod42 Mar 07 '18 at 23:56
  • 1
    Difference between alignment and padding? – Iliketoproveit Mar 07 '18 at 23:57
  • 2
    an offset of 12 bytes from the beginning of the structure will not correctly 64-bit align the uint64. Adding in 4 extra bytes of padding will offset the uint64 by 16 bytes from the beginning and align. – user4581301 Mar 08 '18 at 00:00
  • 2
    Padding is used to ensure that alignment is respected. – Jarod42 Mar 08 '18 at 00:00
  • I would like to understand why this question is downvoted, I did ask a clear question didn't I? – Iliketoproveit Mar 08 '18 at 01:05
  • @roscoe read this https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member –  Mar 08 '18 at 02:26
  • Possible duplicate of [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) –  Mar 08 '18 at 02:26

1 Answers1

0

Yes, there are alignment differences when compiling 32 & 64 bit code, though there isn't, as far as I know, anything in the standard that will tell you how they are different.

What you are likely seeing is that the uint64_t is being aligned on an 8 byte boundary, and there are 4 bytes of padding between B.var3 and B.var5.

Of course, I could be wrong, the padding could be anywhere.

evan
  • 1,463
  • 1
  • 10
  • 13