P
P
prometian2014-10-06 11:31:57
C++ / C#
prometian, 2014-10-06 11:31:57

Why is there no swearing at modifying a third-party piece of memory?

Good afternoon!
The following code declares and initializes an array, as well as a pointer to an array.
Initially, the pointer is at the beginning of the array and increments until it reaches the address of the last element.
Why, if we declared 500 elements, and the first one starts at index 0, does the program quietly let us go beyond the array and modify the memory?
Am I right in thinking that in the case of pointers, no check is carried out at all and an error may or may not occur, but the while (pTmp != &tmp[499]) condition should be correct?
How can you check that a piece of memory is writable without throwing an error or try catch is the only way?
int32_t tmp[500];
int32_t * pTmp = tmp;
{
for (int i = 0; i < 500; i++)
{
tmp[i] = i;
}
}
while (pTmp != &tmp[500])
{
*pTmp = *pTmp * 10;
pTmp++;
}
_getch();
return 0;

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Ruchkin, 2014-10-06
@prometian

Writing to an invalid pointer is UB (undefined behavior), i.e. By default, anything can happen. In fact, it is simply written to where they said that it can be thrown as a structural exception (SEH, not to be confused with ordinary C ++ exceptions) on Windows or SIGSEGV on Unixes, or it may not be thrown if writing is possible at this pointer. That. try-catch is not a solution for two reasons:
1. An exception, even if it happens, is not C ++ (although, for example, the studio allows SEH to catch "normal" catch)
2. An exception is not guaranteed
Checking that the memory is writable in the general case is meaningless, since it may well be available, but the address is not an array, but some other data that can nevertheless be overwritten, breaking the program. The solution is not to write where you don't need to, i.e. minimize manipulation of bare pointers without due care and understanding.

G
GavriKos, 2014-10-06
@GavriKos

Verification occurs roughly speaking at the OS level. For example, XP and win7 react differently in case of writing beyond the array limit - the seven most often crashes the application, the seven will work.
In general, checking whether the pointer indicates where it is always on the programmer's conscience. Moreover, it may be quite valid to increase the pointer beyond the first array - for example, if you guarantee that the second array immediately follows the first array.

A
AxisPod, 2014-10-08
@AxisPod

Why should there be a check? Might be worth reading the books first. C/C++ are not the languages ​​where you can learn by scientific poke. C/C++ has no out-of-bounds control, if you want, take Java, C#, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question