In the following piece of code, what does *(int32 *) 0 = 0;
mean?
void function (void) { ... for (;;) *(int32 *) 0 = 0; /* What does this line do? */ }
A few notes:
int32
is typedef
'ed but you shouldn't care too much about it.Int32: This Struct is used to represents 32-bit signed integer. The Int32 can store both types of values including negative and positive between the ranges of -2147483648 to +2147483647. Example : C#
'\0' is referred to as NULL character or NULL terminator It is the character equivalent of integer 0(zero) as it refers to nothing In C language it is generally used to mark an end of a string.
The code is doing the following:
for (;;) // while(true) *(int32 *) 0 = 0; // Treat 0 as an address, de-reference the 0 address and try and store 0 into it.
This should segfault, null pointer de-reference.
EDIT
Compiled and ran for further information:
#include <stdio.h> #include <stdlib.h> #include <stdint.h> int main(void){ *(int32_t *) 0 = 0; printf("done\n"); return 0; }
gcc -g null.c; ./a.out
Program received signal SIGSEGV, Segmentation fault. 0x00000000004004cd in main () at null.c:7 7 *(int32_t *) 0 = 0;
Since the OP states the code was written by experienced compiler engineers, it is possible this is the intent of the code:
*(int32 *) 0 = 0;
is recognized by this specific C implementation as code that causes behavior not defined by the C standard and known to this implementation to be illegal.for (;;)
additionally indicates that this code is never exited.This sort of reasoning is possible only if you have specific knowledge of the internal operation of a C implementation. It is the sort of thing a compiler engineer might include in special headers for a C implementation, perhaps to mark that certain code (such as code after an abort
call) is never reached. It should never be used in normal programming.
1 For example, consider this code:
if (a) for (;;) *(int 32 *) 0 = 0; else foo();
The compiler can recognize that the then-clause is permitted to have any behavior. Therefore, the compiler is free to choose what behavior it has. For simplicity, it chooses it to have the same behavior as foo();
. Then the code becomes:
if (a) foo(); else foo();
and can be further simplified to:
foo();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With