Search code examples
cstructpaddingsizeof

Understanding memory alignment constraints and padding bytes in C


I have following code snippet.

#include<stdio.h>
int main(){
    typedef struct{
        int a;
        int b;
        int c;
        char ch1;
        int d;
    } str;
    printf("Size: %d \n",sizeof(str));
    return 0;
}

Which is giving output as follows

Size: 20

I know that size of the structure is greater than the summation of the sizes of components of the structure because of padding added to satisfy memeory alignment constraints. I want to know how it is decided that how many bytes of padding have to be added. On what does it depend ? Does it depends on CPU architecture ? And does it depends on compiler also ? I am using here 64bit CPU and gcc compiler. How will the output change if these parameters change.

I know there are similar questions on StackOverflow, but they do not explain this memory alignment constraints thoroughly.


Solution

  • It in general depends on the requirements of the architecture. There's loads over here, but it can be summarized as follows:

    Storage for the basic C datatypes on an x86 or ARM processor doesn’t normally start at arbitrary byte addresses in memory. Rather, each type except char has an alignment requirement; chars can start on any byte address, but 2-byte shorts must start on an even address, 4-byte ints or floats must start on an address divisible by 4, and 8-byte longs or doubles must start on an address divisible by 8. Signed or unsigned makes no difference.

    In your case the following is probably taking place: sizeof(str) = 4 (4 bytes for int) + 4 (4 bytes for int) + 1 ( 1 byte for char) + 7 (3 bytes padding + 4 bytes for int) = 20

    The padding is there so that int is at an address that's a multiple of 4 bytes. This requirement comes from the fact that int is 4 bytes long (my assumption regarding the architecture you're using). But this will vary from one architecture to another.