Purpose of pointers
This usually results in a runtime access violation. The following is done: first, 0 is cast to int *
and yields a null pointer. The value 0 is then written to that address (address zero), which causes undefined behavior, usually an access violation.
Effectively this is this code:
int* address = reinterpret_cast<int*>( 0 );
*address = 0;
a source to share
It does not matter. This is mistake. He analyzed it as
(((int)0) = 0)
So trying to assign the value to r. In this case, the right-hand side is casting from 0
to int
(it's already an int, anyway). The result of casting to something that is not a reference is always an rvalue. And you are trying to appropriate it 0
. What to skip Rvalues is object identity. The following would be accomplished:
int a;
(int&)a = 0;
Of course, you can also write it as
int a = 0;
Update . The question was heavily formatted. The actual code was
*(int*)0 = 0
Well, now it's an lvalue. But the main invariant is violated. The Standard says
The l value refers to an object or function
The lvalue you are assigning is neither an object nor a function. The standard even explicitly says that dereferencing a null pointer ( (int*)0
creates such a null pointer) is undefined behavior. Typically the program will crash when trying to write such a dereferenced "object". "Usually" because the dereference action is already undefined by C ++.
Also note that the above is not the same as below:
int n = 0;
*(int*)n = 0;
While the above is writing something where of course there is no object, it will write something that is the result of reinterpreting n to a pointer. The mapping of a pointer's value is implementation-defined, but most compilers simply create a pointer referencing the null address here. Some systems may store data in this location, so this may have a better chance of staying alive - depending on your system. This is not undefined behavior required, but depends on the compiler and the runtime it is called into.
If you understand the difference between the above null pointer dereferencing (only constant expressions evaluated to 0, converted to pointers yield null pointers!) And the lower dereferencing integer value with null overridden, I think you learned something important.
a source to share