使用gcc 4.7:
$ gcc --version
gcc (GCC) 4.7.0 20120505 (prerelease)
代码清单(test.c):
#include <stdint.h>
struct test {
int before;
char start[0];
unsigned int v1;
unsigned int v2;
unsigned int v3;
char end[0];
int after;
};
int main(int argc, char **argv)
{
int x, y;
x = ((uintptr_t)(&((struct test*)0)->end)) - ((uintptr_t)(&((struct test*)0)->start));
y = ((&((struct test*)0)->end)) - ((&((struct test*)0)->start));
return x + y;
}
编译&amp;执行
$ gcc -Wall -o test test.c && ./test
Floating point exception
SIGFPE由第二个赋值(y = ...)引起。在汇编列表中,这条线上有一个分区?请注意,x =和y =之间的唯一区别是转换为(uintptr_t)。
答案 0 :(得分:8)
忽略由于违反标准中的constarints而导致的未定义行为,gcc在这里做的是计算指向char[0]
- &(((struct test*)0)->start)
和&(((struct test*)0)->end)
的两个指针之间的差异,并将其除以差异乘以char[0]
的大小,当然是0,所以你得到除以0。