Chinaunix首页 | 论坛 | 博客
  • 博客访问: 288015
  • 博文数量: 41
  • 博客积分: 2630
  • 博客等级: 少校
  • 技术积分: 702
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-30 15:56
文章分类

全部博文(41)

文章存档

2012年(2)

2011年(2)

2010年(3)

2009年(26)

2008年(8)

我的朋友

分类: C/C++

2009-04-16 11:43:44

 
    when the compiler generates 32-bit code,  it add "padding" elements struct members to make the fields easier to access in terms of run-time performance. The process of adding padding space is called"alignment".     
   
    In general, alignment modules=sizeof(type).
    VC8.0 sets 1 as alignment modules for char, 2 for short, 4 for (int, long, float), and 8 for (long long, double).
    GCC set 1 as alignment modules for char, 2 for short, 4 for the other types. The address is a multiple of alignment modules.
 
    As a result, the struct size may be larger than the sum of members. So always use sizeof struct to read and write a structure. According to ANSI C, the bitfields are not certain to be stored in the specified order(actually GCC and VC is strictly ordered). Anyhow, it's a good habit to put big data behind.
 
Experiment:

struct s1{ char a; short b; double c; };
struct s2{ char a; double c; short b; };

 
Tested by VC 8.0 and MinGW,
sizeof(struct s1)=16, sizeof(struct s2)=24
 
Tested by GCC 4.3.2 on the Linux platform,

#include <stdio.h>
#include <stdlib.h>

struct s1{ char a; short b; double c; };
struct s2{ char a; double c; short b; };

int main()
{

    struct s1 tmp1;
    struct s2 tmp2;

    printf("sizeof(s1)=%d\n", sizeof(struct s1));
    printf("address of &tmp1 is= %p\n", &tmp1);
    printf("address of tmp1->a= %p \t offset of tmp1->a= %lu\n", &tmp1.a, (long) &((struct s1 *)0)->a);
    printf("address of tmp1->b= %p \t offset of tmp1->b= %lu\n", &tmp1.b, (long) &((struct s1 *)0)->b);
    printf("address of tmp1->c= %p \t offset of tmp1->c= %lu\n\n", &tmp1.c, (long) &((struct s1 *)0)->c);

    printf("sizeof(s2)=%d\n", sizeof(struct s2));
    printf("address of &tmp2 is= %p\n", &tmp2);
    printf("address of tmp2->a= %p \t offset of tmp2->a= %lu\n", &tmp2.a, (long) &((struct s2 *)0)->a);
    printf("address of tmp2->c= %p \t offset of tmp2->c= %lu\n", &tmp2.c, (long) &((struct s2 *)0)->c);
    printf("address of tmp2->b= %p \t offset of tmp2->b= %lu\n\n", &tmp2.b, (long) &((struct s2 *)0)->b);

    return 0;
}

/*
sizeof(s1)=12
address of &tmp1 is= 0xbfb387d8
address of tmp1->a= 0xbfb387d8 offset of tmp1->a= 0
address of tmp1->b= 0xbfb387da offset of tmp1->b= 2
address of tmp1->c= 0xbfb387dc offset of tmp1->c= 4

sizeof(s2)=16
address of &tmp2 is= 0xbfb387c8
address of tmp2->a= 0xbfb387c8 offset of tmp2->a= 0
address of tmp2->c= 0xbfb387cc offset of tmp2->c= 4
address of tmp2->b= 0xbfb387d4 offset of tmp2->b= 12
*/

The memory layout:
阅读(1820) | 评论(1) | 转发(0) |
0

上一篇:双向循环链表

下一篇:HTTP学习笔记

给主人留下些什么吧!~~

chinaunix网友2009-06-16 11:02:01

good~~