Glenn Teitelbaum
Glenn Teitelbaum

Reputation: 10343

C++ is it legal to take the address of 2 or more past the end of the array?

From Take the address of a one-past-the-end array element via subscript: legal by the C++ Standard or not?

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

Why would 2 or 2,000,000 past the end be an issue if it's not derefferenced?

Looking at some simple loop:

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 this become undefined, in practice it just sets a ptr to some value, why would it be undefined if it's not refferenced?

More specifically - what example of anything but what is expected to happen could there be?

Upvotes: 6

Views: 245

Answers (3)

Joseph Mansfield
Joseph Mansfield

Reputation: 110738

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

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

So you have undefined behaviour even if you don't perform indirection on the pointer (not to mention that you do perform indirection, due to the expression equivalence I gave at the beginning).

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385305

in practice it just sets a ptr to some value

In theory, just having a pointer that points somewhere invalid is not allowed.

Pointers are not integers: they are things that point to other things, or to nullity.

You can't just set them to whatever number you like.

in this example, there is nothing but assignment and then qualified dereferrencing - the value is only used if validated, the question is why is the setting of the value an issue?

Yeah, you'd have to be pretty unlucky to run into practical consequences of doing that. "Undefined behaviour" does not mean "always crash". Why should the standard actually mandate semantics for such an operation? What do you think such semantics should be?

Upvotes: 3

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154005

The key issue with taking addresses beyond the end of an array are segmented architectures: you may overflow the representable range of the pointer. The existing rule already creates some level of pain as it means that the last object can't be right on the boundary of a segment. however, the ability to form this address was well established.

Upvotes: 8

Related Questions