E
E
Eugene Ordinary2020-07-30 02:14:07
C++ / C#
Eugene Ordinary, 2020-07-30 02:14:07

The reference is initialized with a dereferenced pointer. Why such behaviour?

int x = 5;
int *px = &x;
int &rx = *(px+1000);
rx = 7; // ошибка иногда


If the pointer px is shifted by a small number, for example, by 10, then an error does not occur during the execution of the operation ra = 7, if it is moved by a large number, for example, by 1000, then it occurs. What does it depend on? What are we going beyond in memory?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Zhilin, 2020-07-30
@evgeniy8086

Let me remind you once again that it does not matter whether the program remains alive, writing to such a pointer is Undefined Behavior. This means, formally, the program can format a hard drive or summon demons. Why the compiler or the program does not catch such errors is expensive to check memory access, so you have to fully trust that you know what you are doing.
Note that this is also undefined behavior:

int a = 1;
int b = 2;
*(&a + 1) = 42;

It is allowed to move by pointers only within the array.
UPD: Even the addition operation itself, without dereferencing, is already UB ( proof ):
*(&a + 2 - 2) = 42; // UB

N
none7, 2020-07-30
@none7

The stack (storage of local variables and return addresses from functions) is shifted from top to bottom( stack -= sizeof(struct allvalrs) / sizeof(void*)). That is, when a new thread is started, its stack pointer is at the top. Accordingly, your code places variables just below the top and any significant plus leads the pointer to an unallocated memory area.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question