【发布时间】:2014-10-13 05:24:48
【问题描述】:
C题:
malloc 结构是否总是导致内部数据从上到下线性放置?作为第二个小问题:填充大小是否有标准,还是在 32 位和 64 位机器之间有所不同?
使用此测试代码:
#include <stdio.h>
#include <stdlib.h>
struct test
{
char a;
/* char pad[3]; // I'm assuming this happens from the compiler */
int b;
};
int main() {
int size;
char* testarray;
struct test* testarraystruct;
size = sizeof(struct test);
testarray = malloc(size * 4);
testarraystruct = (struct test *)testarray;
testarraystruct[1].a = 123;
printf("test.a = %d\n", testarray[size]); // Will this always be test.a?
free(testarray);
return 0;
}
在我的机器上,大小始终为 8。因此我检查 testarray[8] 以查看它是否是第二个结构的 'char a' 字段。在这个例子中,我的机器返回 123,但这显然不能证明它总是如此。
C 编译器是否保证结构是按线性顺序创建的?
我并不是说这样做的方式是安全的或正确的方式,这是一个好奇的问题。
如果它变成 C++,这会改变吗?
更好的是,如果它 malloc'd 到 0x00001000,我的记忆会是这样吗?
0x00001000 char a // First test struct
0x00001001 char pad[0]
0x00001002 char pad[1]
0x00001003 char pad[2]
0x00001004 int b // Next four belong to byte b
0x00001005
0x00001006
0x00001007
0x00001008 char a // Second test struct
0x00001009 char pad[0]
0x0000100a char pad[1]
0x0000100b char pad[2]
0x0000100c int b // Next four belong to byte b
0x0000100d
0x0000100e
0x0000100f
注意:这个问题假设 int 是 32 位
【问题讨论】:
-
malloc只是占用内存,与您的问题中的任何内容都没有真正的关系。使用静态数组而不是malloc,您的问题中的所有内容都可能完全相同。
标签: c pointers struct malloc padding