Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why structure padding is not happening properly?

Tags:

c

padding

#include<stdio.h>

struct A
{
    char        c;
    double      e;
    int         s;
}A;

int main()
{
    printf("%u\n", sizeof(A));
    return 0;
}

It is giving output 16. Shouldn't it be 24 if we consider structure internal padding and structure padding as a whole?

I am compiling the code on Ubuntu 14.04 32 bit with GCC 4.8.2.

like image 948
Jagdish Avatar asked Apr 25 '15 05:04

Jagdish


1 Answers

Your calculations assume that double needs to be 8-byte aligned. That's not the case on all architectures.

On 32bit x86 Linux with GCC, double will be 4-byte aligned by default. You can change that with the -malign-double flag to make it 8-byte aligned.

So the layout assuming defaults on 32bit x86 Linux:

char       // 1 byte
           // 3 byte padding
double     // 8 bytes
int        // 4 bytes

So a total of 16 bytes, with 3 bytes of padding in the middle.

The Wikipedia article Data structure alignment has size/alignment numbers for various types on 32bit x86 and 64bit x86_64 in a few compilers/environments.

like image 133
Mat Avatar answered Sep 19 '22 09:09

Mat