6
#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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Jagdish
  • 1,848
  • 3
  • 22
  • 33
  • 2
    Why should it be 24? – Mat Apr 25 '15 at 05:46
  • 2
    `1+3pad + 8 + 4 --> 16` Looks good 4-byte alignment to me. – chux - Reinstate Monica Apr 25 '15 at 05:47
  • 1
    I think OP was expecting double to be aligned by 8 bytes. – holgac Apr 25 '15 at 05:48
  • 1
    @Mat, 1 byte for c + 7 byte padding + 8 byte for e + 4 byte for s + 4 byte for structure alignment if we declare array of structure and want to aligned internal members aligned in that case also. Please correct me if i am wrong. – Jagdish Apr 25 '15 at 05:49
  • 1
    Compiling with OS X 10.9.5 using gcc 4.2.1 I get 24. – Patrick Roberts Apr 25 '15 at 05:56
  • 2
    Check [this general answer](http://stackoverflow.com/a/11110283/669567) , [this specific answer](http://stackoverflow.com/questions/14893802/why-is-a-double-member-in-struct-not-aligned-on-8-byte-boundary) and [a discussion to blow your mind](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=10645) – holgac Apr 25 '15 at 05:58
  • 1
    Note that the padding *is* happening *properly*; it's just not happening as *you expected*. – Kyle Strand Apr 25 '15 at 06:10

1 Answers1

12

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • I've never heard of byte aligning before. Why do C structs do this? – Patrick Roberts Apr 25 '15 at 05:58
  • @Patrick, You can read on how cpu accesses memory. Google it. – Jagdish Apr 25 '15 at 06:03
  • Added a link to the Wikipedia article. Short version: CPUs need this. Unaligned accesses are either not possible or slow @PatrickRoberts – Mat Apr 25 '15 at 06:04
  • So GCC doesn't check what the native alignment should be? – Kyle Strand Apr 25 '15 at 06:13
  • @KyleStrand: x86_64 supports 32bit-aligned accesses to 64bit floats, so that works (and probably saves some memory in some programs). There might be cases (CPU generations) when that's not optimal performance-wise (I don't know), and you have that switch if it matters for you. – Mat Apr 25 '15 at 06:18