Is C ++ legal to accept an address of 2 or more as the end of an array?

From Take the address of an element of the array "one after the past" by index: legal according to the C ++ standard or not?

It seems that there is a language specific to address one than the end of the array.

Why will 2 or 2,000,000 eventually be a problem if it is not canceled?

Let's look at a few simple loops:

int array[]; ... for (int i = 0: i < array_max; ++i) { int * x = &array[i *2]; // Is this legal int y=0; if (i * 2 < array_max) // We check here before dereference { y = *x; // Legal dereference } ... } 

Why or at what point does it become undefined, in practice, it simply sets the ptr value for some value, why should it be undefined if it has not been referenced?

In particular, what kind of example can there be nothing but the expected?

+6
source share
3 answers

The key problem when accepting addresses outside the array is segmented architecture: you can overflow the representable range of the pointer. The existing rule already creates a certain level of pain, as this means that the last object cannot be right at the boundary of the segment. however, the ability to form this address has been well established.

+8
source

Since array[i *2] equivalent to *((array) + (i*2)) , we should look at the rules for adding a pointer. C ++ 11 §5.7 states:

If both pointer operands and the result point to elements of the same array object or one after the last element of the array object, the evaluation should not lead to overflow; otherwise, the behavior is undefined.

That way, you have undefined behavior even if you don't follow the indirect reference to the pointer (not to mention that you are doing the indirect call, due to the equivalence of the expression that I gave at the beginning).

+4
source

in practice, it just sets ptr to some value

In theory, a pointer that indicates somewhere invalid is simply not indicated.

Pointers are not integers: this is something that points to other things or to invalidation.

You cannot just set them to any number you like.

in this example, there is nothing but assignment and then qualified dereferrencing - the value is used only if it is confirmed, the question arises, why is the parameter value a problem?

Yes, you must be very unlucky to face the practical consequences of this. “Undefined behavior” does not mean “always crashing”. Why should a standard impose semantics for such an operation? What do you think should be such semantics?

+3
source

All Articles