Purpose of pointers

What's the point

*(int *)0 = 0; 

      

It compiles successfully

0


a source to share


5 answers


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;

      

+3


a source


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.

+4


a source


Compilation error. You cannot change non-lvalues.

+1


a source


It puts zero on the zero address. On some systems, you can do this. Most MMU based systems will not allow this at runtime. I once saw that the embedded OS writes address 0 when doing time (NULL).

+1


a source


there is no valid l value in this operation, so it should not compile.

the left side of the assignment should be ... err ... assignable

0


a source







All Articles