1

I have the structure

typedef struct EData
{
    int a;
    char c;
}
Edata obj;

a is the integer variable so it takes 4 bytes and the c is the char variable so it takes 1 byte, totalling 5 bytes

But when I print sizeof(obj) it shows 8 bytes.

What is the reason?

moinudin
  • 134,091
  • 45
  • 190
  • 216
Rajesh Kumar G
  • 1,424
  • 5
  • 18
  • 30
  • 2
    Essentially a duplicate of [How do I find the size of a struct?](http://stackoverflow.com/questions/143025/how-do-i-find-the-size-of-a-struct) – Chris Lutz Dec 31 '10 at 10:21

4 Answers4

4

Because on 32bit systems memory is aligned at 4byte (32bit) boundaries so it has to multiple of 4bytes, see Data structure alignment

ismail
  • 46,010
  • 9
  • 86
  • 95
  • 1
    Not quite... not *all* memory is aligned at 4-byte boundaries. For example, a struct that only contained `char` elements could easily have a size that is not a multiple of four. – psmears Dec 31 '10 at 10:28
  • Wouldn't that produce a non-aligned memory access while accessing such an element? – ismail Dec 31 '10 at 10:29
  • Also you could use `#pragma pack(1)` on Visual Studio to set alignment to 1 byte. Then you should get 5 bytes as `sizeof(Edata)`. – RedX Dec 31 '10 at 10:43
  • No - whether a memory access is aligned or not depends both on the address, and on the size of the object being accessed. A single-byte element is correctly-aligned whatever alignment it is stored at, so a structure consisting entirely of single-byte elements is also correctly-aligned at any address. – psmears Dec 31 '10 at 12:05
3

int is 4 bytes, char is 1 byte. However, your compiler aligns each struct to a word (a word is 4 bytes on 32 bit architecture) as it improves performance. Therefore each instance of EData will be rounded up to 2 words (or 8 bytes).

What you end up with is something like this:

typedef struct EData {
    int a;
    char c;
    char padding[3];
}
moinudin
  • 134,091
  • 45
  • 190
  • 216
1

The increase in size you notice is due to compiler's padding.
Compiler adds extra bytes to enforce correct byte boundaries.
So compiler adds the extra bytes to enforce the proper location for each member according to its type.
There is an option to stop compiler to do this (packed directive) but it is best to avoid it (except in corner-cases)

Cratylus
  • 52,998
  • 69
  • 209
  • 339
0

If it's a problem for you, you can either use #pragma or a compiler switch (a variety of compilers has such a switch).

sjngm
  • 12,423
  • 14
  • 84
  • 114