So the line of code in question is:
*((int*)(0))=1;
Because I have so little experience with C/C++ and haven't tried very hard, I don't understand this simple expression. What does it mean exactly?
It's meant to crash the program, typically useful during debugging.
It'll dereference the NULL pointer and attempt to assign a value to that memory, which is theoretically just undefined behavior, but will result in an access violation exception on 99% of systems.
Typically, it's found in cases such as:
if ( !FileRead(importantFile) )
{
// this should never happen, critical exception
*((int*)(0))=1;
}
Break it down piece by piece. Inside the outer brackets on the left, you have:
(int*)(0)
This is a C-style cast of the value 0 to a pointer to int; creating a null pointer, in effect.
Let's add a variable to capture the result of this first expression:
int* x = (int*)(0);
The outer part is now:
*(x) = 1;
This is dereferencing the pointer x, and assigning 1 to the resulting int.
Since (in this case) x is a null pointer, this will crash on dereference (strictly speaking, it will crash on the assignment following the dereference - see comments below). It's typically used to force a crash or other system-dependent undefined behaviour; usually for testing or debugging purposes. You wouldn't want a line like this in your production code.
Note: There are some architectures, usually in embedded systems, where zero is a valid memory address, and the code above may have a legitimate purpose. However, if you were working on such a platform, it is unlikely that you would struggle with the syntax in the question.
As others have noted, it's a way to drop into the debugger. Most computers will refuse to write to memory address 0
and will enter some kind of diagnostic mode instead.
However, a better alternative is the standard function raise()
, from <signal.h>
or <csignal>
. raise( SIGSEGV )
will produce the same result as your example intends to, even on computers that do allow writing to address zero (such machines do exist!) and compilers with liberal interpretation of undefined behavior. That operation is not guaranteed or required to crash. From the compiler's perspective it might as well do nothing, and it would not be incorrect to simply delete it from the compiled program.
For a more descriptive signal value, see man signal
. What is meant is probably raise( SIGTRAP )
, or abort()
. The latter is equivalent to raise( SIGABRT )
on my system, but I'm lazy to check whether that equivalency is guaranteed by POSIX or the C language.
This stores something at null pointer (and causes SEGFAULT). Useful for stopping the program and calling debugger while preserving all memory contents etc.