您的位置:首页 > 其它

三谈内存对齐问题

2009-06-04 08:22 211 查看
请同时参考:

1. 关于内存对齐问题

2. 再谈内存对齐问题

内存对齐问题,大家已经说了很多。今天碰到一个帖子,内涵内存对齐问题,大家争论得比较激烈,在争论的过程中,加深了对这个问题的认识。

第一种情况:

struct BBB

{

long num; // 4bytes

char *name; // 4 bytes

short int data; // 2 bytes

char ha; // 1 byte

short ba[5]; // 10 bytes

};

sizeof(BBB) = 24bytes

理由:

1. 很容易知道BBB的内存对齐数是4bytes

2. num和name各为4bytes,已经对齐

2. data和ha加起来是3bytes,因此要补1byte

3. ba共10bytes,因此要补2bytes

第二种情况:

struct BBB

{

long num; // 4 bytes

char *name; // 4 bytes

short int data; // 2 bytes

char ha; // 1 byte

char hb; // 1 byte

short ba[5]; // 10 bytes

};

sizeof(BBB) = 24bytes

理由:

1. 很容易知道BBB的内存对齐数是4bytes

2. num和name各为4bytes,已经对齐

2. data、ha和hb加起来是4bytes,已经对齐

3. ba共10bytes,因此要补2bytes

第三种情况:

struct BBB

{

char hb; // 1 byte

long num; // 4 bytes

char *name; // 4 bytes

short int data; // 2 bytes

char ha; // 1 byte

short ba[5]; // 10 bytes

};

sizeof(BBB) = 28bytes

理由:

1. 很容易知道BBB的内存对齐数是4bytes

2. hb为1byte,因此需要补3bytes

3. num和name各为4bytes,已经对齐

4. data、ha加起来是3bytes,因此要补1byte

5. ba共10bytes,因此要补2bytes

通过上述三种情况,我们可以得出推论:

a. 尽管成员变量一样,如果由于排列的顺序不同,则所得到对象的大小也有可能不同

b. 相同数据类型的成员变量,在结构或类定义时,尽量相邻,这样可以减少空间的消耗

下面再举一个例子,来说明上述推论b:

假定结构BBB定义如下:

struct BBB

{

char ha;

int a;

char hb;

int b;

char hc;

int c;

};

那么sizeof(BBB) = 24bytes

如果结构BBB的定义改为:

struct BBB

{

char ha;

char hb;

char hc;

int a;

int b;

int c;

};

那么sizeof(BBB) = 16bytes

可见在两种情况下结构BBB所能承载的数据量是一样的,但所占用的空间却有很大的不同。

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/pathuang68/archive/2009/06/03/4240404.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: