1

What would be the size of MyStruct on windows 7 , 64 bit ?

    typedef struct MyStruct_tag
   {
       char        c;
       double      d;
       int         s;
    } MyStruct;

My answer:

1 (Char) + 7 (Padding) + 8 (double) + 4 (int) = 20 bytes 

But the answer is coming out 24 bytes. What is going on ?

user2799508
  • 844
  • 1
  • 15
  • 41

2 Answers2

4

The final int is likely followed by 4 bytes of padding so that the alignment of the double in the next similar struct in an array will be properly aligned.

But ultimately, padding is implementation-defined. Trying to reason about or predict it isn't useful. The compiler should take care of it for you. If it doesn't, strongly reconsider what you're doing.

2

It's for ``alignment''. Many processors can't access 2- and 4-byte quantities (e.g. ints and long ints) if they're crammed in every-which-way.

Suppose you have this structure:

struct  {
    char a[3];
    short int b;
    long int c;
    char d[3];
    };

Now, you might think that it ought to be possible to pack this structure into memory like this:

+-------+-------+-------+-------+
|           a           |   b   |
+-------+-------+-------+-------+
|   b   |           c           |
+-------+-------+-------+-------+
|   c   |           d           |
+-------+-------+-------+-------+

But it's much, much easier on the processor if the compiler arranges it like this:

+-------+-------+-------+
|           a           |
+-------+-------+-------+
|       b       |
+-------+-------+-------+-------+
|               c               |
+-------+-------+-------+-------+
|           d           |
+-------+-------+-------+

In the packed'' version, notice how it's at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it's hard for the processor, too. Therefore, most compilers willpad'' the structure (as if with extra, invisible fields) like this:

+-------+-------+-------+-------+
|           a           | pad1  |
+-------+-------+-------+-------+
|       b       |     pad2      |
+-------+-------+-------+-------+
|               c               |
+-------+-------+-------+-------+
|           d           | pad3  |
+-------+-------+-------+-------+

Courtesy - Steve Summit

iAhmed
  • 6,556
  • 2
  • 25
  • 31