0

I have this stuct declared in C. When I call sizeof(struct pixel), I am told that the size of this struct is 12 Bytes when I expect it to be 7 Bytes (1 for chars and 4 for the int). Why does this happen?

Struct:

   struct pixel {
        unsigned char red;
        unsigned char green;
        unsigned int alpha;
        unsigned char blue;
    };
Tanishq dubey
  • 1,522
  • 7
  • 19
  • 42

3 Answers3

2

The idea is that for speed and cache considerations, operands should be read from addresses aligned to their natural size.

struct pixel {
    unsigned char red;   // 0
    unsigned char green; // 1
    unsigned int alpha;  // 4 (gotta skip to an aligned offset)
    unsigned char blue;  // 8 (then skip 9 10 11)
};

// next offset: 12

The x86 architecture has always been able to fetch misaligned addresses. However, it's slower and when the misalignment overlaps two different cache lines, then it evicts two cache lines when an aligned access would only evict one.

Some architectures actually have to trap on misaligned reads and writes, and early versions of the ARM architecture (the one that evolved into all of today's mobile CPUs) ... well, they actually just returned bad data on for those.

So, alignment is important.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
  • Thanks for the quick response. As a quick followup, is there anyway for this struct to be strictly less than 8 bytes ( I can easily reduce it to just 8) – Tanishq dubey Feb 24 '16 at 06:17
  • But that will just return 8 as the size. Is there a way I can - intentionally - get 7 bytes? – Tanishq dubey Feb 24 '16 at 06:20
  • 2
    @tanishqdubey In case of GCC: [pragma pack](https://gcc.gnu.org/onlinedocs/gcc/Structure-Layout-Pragmas.html#Structure-Layout-Pragmas). MSVC should support it too. – Youka Feb 24 '16 at 06:22
  • 1
    @Youka's advice is right. See, e.g., http://stackoverflow.com/questions/3318410/pragma-pack-effect – DigitalRoss Feb 24 '16 at 06:43
0

In C, structure members are aligned for faster&safer memory access. Your default alignment is 4, so after red and green follow 2 padding bytes (4 bytes block complete), then alpha with 4 bytes and the last byte blue gets padded to become 4 bytes again -> 3x 4 bytes = 12 bytes.

You can change this behaviour by compiler instructions like pragma pack.

Youka
  • 2,646
  • 21
  • 33
  • It works on the 32-bit compilers but not on the 64-bit ones. The 64 bit compilers don't seem to be able to go below pack(4) – cup Jun 30 '21 at 14:33
0

As other several users refers, is a padding problem. See this
The less I think you can reduce this struct is 8 bytes (in x86 processors), either putting the alpha field to beginning or end

Community
  • 1
  • 1