Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align a struct member in D?

I tried this

struct Foo(T)
{
    align(8) void[T.sizeof] data;
}

but

static assert(Foo!(int).data.alignof == 8);

fails, telling me the alignment is still 1 instead of 8.

Why is this, and how do I fix it, so that it works for any arbitrary alignment that is a power of 2 (not just 8)?

like image 529
user541686 Avatar asked May 19 '12 01:05

user541686


People also ask

What do you mean by structure member alignment?

Data structure alignment is the way data is arranged and accessed in computer memory. Data alignment and Data structure padding are two different issues but are related to each other and together known as Data Structure alignment.

Why do structs have padding?

Memory align (for struct) Before each individual member, there will be padding so that to make it start at an address that is divisible by its alignment requirement. E.g., on many systems, an int should start at an address divisible by 4 and a short by 2.

What is structure padding?

Structure padding is a concept in C that adds the one or more empty bytes between the memory addresses to align the data in memory.


1 Answers

Browsing the DMD source, it looks like alignof doesn't take into account align attributes.

Here is where it is handled:

... if (ident == Id::__xalignof)
{
    e = new IntegerExp(loc, alignsize(), Type::tsize_t);
}

This converts a .alignof expression into a size_t expression with value alignsize(), so let's look at alignsize() for a static array:

unsigned TypeSArray::alignsize()
{
    return next->alignsize();
}

It just gets the alignment of the element type (void) in your case.

void is handled by TypeBasic::alignsize(), which just forwards to TypeBasic::size(0)

switch (ty)
{
    ...
    case Tvoid:
        size = 1;
        break;
    ...
}

Looking at how other types handle alignof, it doesn't look like align attributes are taken into account at all, but I could be wrong. It may be worth testing the alignment manually.

like image 63
Peter Alexander Avatar answered Sep 29 '22 06:09

Peter Alexander