-3

What exactly does the following do (or try to do) in C?

*(int *)0='X';

And what signal would be generated? Would it be a SIGSEGV?

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
ymanseur
  • 53
  • 4

2 Answers2

3

The behaviour of *(int *)0='X'; is undefined.

The compiler is free to do anything it pleases. (i) raise a SIGSEGV, (ii) not compiling the line at all are two possibilities.

To generate a fault explicitly, use raise as appropriate (defined in <signal.h>).

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

Putting this into a complete program, segv.c:

int
main(
    void)
{
    *(int *) 0 = 'X';
    return 0;
}

and compiling:

clang -Oz -Wno-error -s -o segv segv.c

Now, when I run it on my 64-bit GNU/Linux system, I do in fact get a segmentation fault:

fish: "./segv" terminated by signal SIGSEGV (Address boundary error)

However, if you are seeking to generate segmentation faults, as some people in comments have pointed out, you should use raise(3) from signal.h.

sadljkfhalskdjfh
  • 747
  • 3
  • 10
  • 17