开发者

About the __alignof struct in c

开发者_开发知识库

the __alignof value is the alignment requirement of the largest element in the structure.

Why??


Where did you get the quote from? If you interpret it literarily, it is plain wrong. For example:

struct s
{
    char array[100];
    long x;
}

Clearly, the alignment of the struct is that of x not of array. The rule should read:

The alignment of a struct is the same as the element with the highest alignment.

Now, over to the real question, why do the struct have to have this alignment? Well, imagine that you have a struct and access a member inside it. If the struct would have less alignment than the embedded member, accessing the member could be done in an unaligned manner, which typically would trigger a runtime error from the underlying hardware.


Because memory subsystems can't fetch any piece of data aligned to any address.

The natural boundary of a piece of data is such that

address % sizeof(x) == 0

That way you don't have to do two data bus fetches for an element that can be had in one data bus fetch.

That __alignof returns the alignment of the largest item has to do with the idea that if the largest item is aligned, then the smaller items will pack into the alignment guides since they are, well, smaller than the bounds of the largest item.


Using the default structure layout rules that most compilers use, padding gets inserted in your structure so that each field in the structure has native alignment - that is, every field that is equal to or larger than the native word size for the target machine gets put on a word boundary. Making sure that layout takes place correctly requires the entire structure to be aligned to that same amount.

You didn't say what compiler you're using, but it sounds like it aligns objects even further than the architecture might require. At any rate, the __alignof documentation is just letting you know what it will return when you pass a structure to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜