Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code cause a Floating point exception - SIGFPE

Using gcc 4.7:

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

Code listing (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 & execute

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

The SIGFPE is caused by the second assignment (y = ...). In the assembly listing, there is a division on this line? Note that the only difference between x= and y= is casting to (uintptr_t).

like image 699
Wade Avatar asked Feb 20 '23 01:02

Wade


1 Answers

Disregarding the undefined behaviour due to violation of constarints 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 that difference by the size of a char[0], which of course is 0, so you get a division by 0.

like image 178
Daniel Fischer Avatar answered Mar 09 '23 21:03

Daniel Fischer