Why this code throws a floating point exception - SIGFPE

Using gcc 4.7:

$ gcc --version gcc (GCC) 4.7.0 20120505 (prerelease) 

Code List (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; } 

Compile and execute

 $ gcc -Wall -o test test.c && ./test Floating point exception 

SIGFPE is called the second destination (y = ...). Is there a division in the assembly sheet on this line? Note that the only difference between x = and y = is to call (uintptr_t).

+4
source share
1 answer

Without considering undefined behavior due to a violation of constants in the standard, what gcc does here is to calculate the difference between two pointers to char[0] - &(((struct test*)0)->start) and &(((struct test*)0)->end) and divide this difference by the size of char[0] , which, of course, is 0, so you get a division by 0.

+8
source

Source: https://habr.com/ru/post/1436240/


All Articles