Вопрос

The scope is in x86
For example, we have a struct like this:

struct X{
   int    a;   
   char   b; 
               // compiler will pad 3 bytes here
   double c;
};
X x;

I think the alignment of x should be the largest member in it, in this case is double, which is 8 bytes,
so &x should be a multiple of 8, am I right?

However, after some tests, my compiler(msvc 2013) says &x can also be a multiple of 4 but not 8.

Isn't it meaning &x.c will also be a multiple of 4?

Where do I misunderstand?

Это было полезно?

Решение

The C and C++ standards does not give any advice [or at least no firm rules] on what alignment should be. It is up to each compiler (and of course, what target the compiler is for) to determine a good policy. It's often preferred if this policy works for the target... ;)

Since the FPU [including SSE in scalar mode] of x86 can read "double" from any byte-address and I believe there is no direct benefit in adding more than 3 bytes between the b and c elements, nor to align the whole struct to anything more than 4 bytes. Doing more would waste memory.

In some other architecture, it may well be a great benefit (or a requirement for the target to operate correctly), and it would thus align the whole struct to 8 bytes.

Другие советы

Structure alignment in VC is a compiler option /Zp determines the byte boundaries on which your structures will be packed. This is normally an advanced option and not used except in unusual use cases (such as doing a memcpy of block data for transfer over the network). Check the property pages of the project in order to see what the alignment is.

http://msdn.microsoft.com/en-us/library/xh3e3fd0.aspx

Generally speaking you can't say that much about the size, the alignment or how your struct is packed, and by "generally" I mean according to the C++ standard of your choice.

The problems are:

  • int, char and double have no defined size according to the standard, the standard simply sets some minimum requirements, what you are going to get depends on the implementation
  • alignment depends not only on the compiler implementation but sometimes even on the set of flags that you are passing and what hardware you are targeting, packing is extremely important for the CPU cache and some instructions may even need different padding, this also depends on what you are putting in the struct and how you are writing it.

As a consequence for this kind of operations you have to literally stick with the documentation of the compiler of your choice and dive into the features that it provides you, for example here you can find an overview on how to pack data in gcc vs msvc .

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top