开发者

padding at last member of c struct

开发者 https://www.devze.com 2023-03-31 22:41 出处:网络
I always assume, as they said here http://en.wikipedia.org/wiki/Data_structure_alignment, \"It is important to note that the last member is padded with the number of bytes required so that the total s

I always assume, as they said here http://en.wikipedia.org/wiki/Data_structure_alignment, "It is important to note that the last member is padded with the number of bytes required so that the total size of the structure should be a multiple of the largest alignment of any structure member"

So for the struct like this, its size should be 16 at a 32 processor

typedef struct
{
   double   s;  /* 8 bytes */
   char     c;  /* 7 bytes padding at开发者_C百科 the end of make the total size 8*2 */
} structa_t;  

So I was quite surprised to the size is 12 instead of 16!! Why is that ? Can someone cast some light on it ?

sizeof(double) = 8
sizeof(structa_t) = 12

BTW, so system info

$ uname -a
Linux 2.6.18-8.el5xen #1 SMP Thu Mar 15 21:02:53 EDT 2007 i686 i686 i386 GNU/Linux
$ gcc --version
gcc (GCC) 4.1.1 20070105 (Red Hat 4.1.1-52)


The key wording here is:

...the total size of the structure should be a multiple of the largest alignment of any structure member...

On your system, the aligment of a double is 4, not 8.

If you wait for C1x, you can use the _Alignof operator (similar to sizeof). On your system,

sizeof(double) == 8
_Alignof(double) == 4

You can test the alignment in a more primitive way in C89,

#include <stdlib.h>
struct char_double { char x; double y; };
#define DOUBLE_ALIGNMENT offsetof(struct char_double, y)

Or with a macro,

#define alignof(x) offsetof(struct { char a; x b; }, b)


Wikipedia isn't a particularly reliable source for details like this.

In this case, the size of the largest item in the struct forms a (fairly hard) upper bound in the size to which the struct as a whole might get padded -- but the implementation is free to use less padding than that if it sees fit. In many cases, an "N-bit" processor, the maximum padding that can do any good for a particular struct will be the smaller of: 1) the largest item in the struct, or 2) the 'bitness' of the processor itself (so with a 32-bit processor, you frequently don't need/want to pad to larger than 32-bit boundaries, even for data items larger than that).


Its because in your case the structure is aligned to word boundaries (where a word = 4 bytes).

0

精彩评论

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

关注公众号