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?
'\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.
It means that a pointer variable my_pointer is pointing (it is containing the address of) to my_variable. If my_variable is an integer, then, when you declare your pointer, it must also be an integer pointer.
int(*ret)() declares a function pointer named ret ; the function takes unspecified arguments and returns an integer. (int(*)())code. casts the code array to a function pointer of that same type. So this converts the address of the code array to a function pointer, which then allows you to call it and execute the code.
The ret instruction transfers control to the return address located on the stack. This address is usually placed on the stack by a call instruction. Issue the ret instruction within the called procedure to resume execution flow at the instruction following the call .
This is a C-style cast of the value 0 to a pointer to int; creating a null pointer, in effect. 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.
Exiting in a debugger-friendly way has a name: abort (). About OP's question, it's undefined behaviour to assign something to the NULL pointer; therefore, the compiler is allowed to deduce that that line of code leads to undefined behaviour and optimize it out altogether. Break it down piece by piece.
Inside the outer brackets on the left, you have: This is a C-style cast of the value 0 to a pointer to int; creating a null pointer, in effect. This is dereferencing the pointer x, and assigning 1 to the resulting int.
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;
}
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