积极答复者
内存分配问题

问题
-
c++中数据结构的成员如何进行内存分配,他们分配时对齐有何规则可遵循?
例如 32位机下 VC sizeof()函数, 为什么会出现下面的情况?
struct test1 //该结构的变量占空间24字节
{ char c;
double a;
int b;
char d;
} tes1 ;
struct test2 //该结构的变量占空间16字节
{ double a;
int b;
char c;
char d;
} tes2;
struct test3//该结构的变量占空间24字节
{ double a;
char c;
int b;
char d;
} tes3;
答案
-
Windows系统是这样的,简单的规则如下
1.按照2的次方对齐
2.对齐后剩余空间可以放下,那么就放到剩余的空间中,
3.放不下,就单独开辟一块和所需最接近的2的n次方大小的内存来保存.
结构一:
char 1个字节(和下面对齐实际占用8个)
double 8个字节
int 4个字节
char 1个字节(和上面的int对齐,占用4个字节)
结构3:
c占用8个字节,但实际占用1个字节,所以可以放下b,但是c和b对齐,那么c实际用了4个字节
d和double对齐,占用8个字节
0xBAADF00D- 已建议为答案 Nancy Shao 2010年3月30日 8:25
- 已标记为答案 Nancy Shao 2010年4月5日 1:28
-
没有规则。C++标准中明确规定这些是标准之外的东西,每个编译器可以自由决定。
The following is signature, not part of post
Please mark the post answered your question as the answer, and mark other helpful posts as helpful.
Visual C++ MVP- 已建议为答案 Nancy Shao 2010年3月30日 8:25
- 已标记为答案 Nancy Shao 2010年4月5日 1:28
-
同意蒋晟的说法,这个跟每个编译器有关,C++标准中没有明确定义。你可以在网上搜一下关于内存对齐的问题,会找到很多相关的信息。
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.- 已标记为答案 Nancy Shao 2010年4月5日 1:28
-
全部回复
-
没有规则。C++标准中明确规定这些是标准之外的东西,每个编译器可以自由决定。
The following is signature, not part of post
Please mark the post answered your question as the answer, and mark other helpful posts as helpful.
Visual C++ MVP- 已建议为答案 Nancy Shao 2010年3月30日 8:25
- 已标记为答案 Nancy Shao 2010年4月5日 1:28
-
Windows系统是这样的,简单的规则如下
1.按照2的次方对齐
2.对齐后剩余空间可以放下,那么就放到剩余的空间中,
3.放不下,就单独开辟一块和所需最接近的2的n次方大小的内存来保存.
结构一:
char 1个字节(和下面对齐实际占用8个)
double 8个字节
int 4个字节
char 1个字节(和上面的int对齐,占用4个字节)
结构3:
c占用8个字节,但实际占用1个字节,所以可以放下b,但是c和b对齐,那么c实际用了4个字节
d和double对齐,占用8个字节
0xBAADF00D- 已建议为答案 Nancy Shao 2010年3月30日 8:25
- 已标记为答案 Nancy Shao 2010年4月5日 1:28
-
同意蒋晟的说法,这个跟每个编译器有关,C++标准中没有明确定义。你可以在网上搜一下关于内存对齐的问题,会找到很多相关的信息。
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.- 已标记为答案 Nancy Shao 2010年4月5日 1:28
-