【发布时间】:2017-03-31 06:41:49
【问题描述】:
我不确定这是正常现象还是编译器错误,但我有一个包含很多成员的 C 结构。其中,有:
struct list {
...
...
const unsigned char nop=0x90; // 27 bytes since the begining of the structure
const unsigned char jump=0xeb; // 28 bytes since the begining of the structure
const unsigned char hlt=0xf4; // 29 bytes since the begining of the structure
unsigned __int128 i=0xeb90eb90eb90eb90f4f4 // should start at the 30th byte, but get aligned on a 16 byte boundary and starts on the 32th byte instead
const unsigned char data=0x66; // should start at the 46th byte, but start on the 48th instead.
}; // end of struct list.
我很难找出为什么我的程序无法运行,但我终于发现 hlt 和 i 之间有 2 个字节的间隙,设置为 0x0。这意味着 i 正在对齐。
当我 printf 结构的那部分时,这一点非常清楚,因为使用:
for(int i=28;i<35;i++)
printf("%02hhX",buf[i]);
我在屏幕上看到EBF40000EB90EB90。
我在我的程序中尝试了volatile struct list data;之类的东西,但它并没有改变对齐问题。
那么是否有#pragma 或__attribute__ 来告诉gcc 不要在struct listtype 中对齐i?
【问题讨论】:
-
对我来说这看起来像是一个语法错误。这是 C++ 还是什么?
-
这不是错误。在 C 中,每个结构成员后面都可以有未指定的填充。为什么会出现这个问题?
-
XY 问题。 为什么你要打包
struct?如果这是用于存储或序列化:定义帧格式并使用移位进行序列化。 -
这绝不是stackoverflow.com/questions/2554229/…投票重新开放的副本。