Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does type alignment modify type size?

Tags:

c++

I wrote following code and tested it on gcc:

// firstly some platform-specific workarounds
#if _MSC_VER
#define ALN_BEGIN(x) __declspec(align(x)) 
#define ALN_END(x)
#define alignof(x) __alignof(x)
#else
#define ALN_BEGIN(x)
#define ALN_END(x) __attribute__((aligned(x)))
#define alignof(x) __alignof__(x)
#endif

// struct have three 4-byte members, but aligned at 32 byte
ALN_BEGIN(32) struct Foo
{
    float a;
    float b;
    float c;
} ALN_END(32);

// show its size and alignment
int main(int argc, char** argv)
{
    printf("size %d, alignment%d\n", sizeof(Foo), alignof(Foo));
}

When I compile it using gcc and run, although Foo only has 12 bytes for all its members, sizeof(Foo) got 32 which is alignment size. So does the size expansion is according to language standard (which is reliable) or it is only a feature for GCC?

I'm making an object pool class, so I have to precisely work with type size and alignment.

like image 783
jiandingzhe Avatar asked Dec 24 '22 13:12

jiandingzhe


2 Answers

Yes, this is consistent with the standard. sizeof (X) is basically defined as the offset in bytes between the starting addresses of two consecutive X objects in an array. If such objects cannot follow each other tightly due to alignment restrictions, sizeof increases accordingly.

Quoting C++14, 5.3.3/2:

... When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array. ... When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.

(Emphasis mine)

like image 117
Angew is no longer proud of SO Avatar answered Jan 08 '23 19:01

Angew is no longer proud of SO


The result of sizeof, for any type (except char types, which have size 1 by definition), is implementation defined, and is affected by alignment. However, if

  • sizeof(float) is 4;
  • your struct contains three floats; AND
  • both beginning and end of the struct are aligned to 32 byte boundaries.

then you can expect the behaviour you see.

like image 32
Peter Avatar answered Jan 08 '23 17:01

Peter