Home > Mobile >  How does structure padding work in ESP32's compiler
How does structure padding work in ESP32's compiler

Time:10-22

I was talking with a friend and trying out different structure configurations. And looking at the outputs has me confused as to how the structure is being padded. I'm using wokwi's online esp32 compiler for this. The structure configurations that have me confused are:

struct bruh{
  short int aK;
  short int a;
  char cd;
}; 
//Printing the size of this structure gives the output as 6. 
// I would have assumed either 8(padded) or 5(packed). Why?

The other example that has me puzzled is:

struct bruh{  
    int aK;  
    char cd;  
}; 
//Output is 8. Understandable. 
//Int is 4 bytes, and the extra character gets padded to the next 4 bytes.

but!

struct bruh{  
    char cd;  
}; 
//Gives me the output as 1. If the example before this one is getting
// padded because of the additional character byte, why isn't this structure 4 bytes?

CodePudding user response:

Padding is not to bring the size up to the next multiple of 4, it is to ensure every member is always on the correct alignment. Different types have different alignment requirements, and these are all implementation-defined.

You can use the alignof operator to look at the alignment of a type.

Here's one compiler reporting what it does with your types

  • Related