bitsequence35
bitsequence35

Reputation: 51

Is it undefined behavior to get the address of an array element that is out of bounds?

Let's say we allocate a byte array of 10 elements. Accessing any element within bounds is defined.

I understand that reading and writing elements out of bounds is undefined behavior. Is it undefined behavior to get the address of an array element that is out of bounds?

Example:

#include <stdint.h>
#include <string.h>

int main(void)
{
    uint8_t buf[10];
    memset(buf, 0, sizeof(buf));

    // Defined behavior
    uint8_t a_value = buf[9];

    // Defined behavior
    buf[0] = 1;

    // Undefined behavior?
    uint8_t *addr = &buf[10];
}

Upvotes: 5

Views: 241

Answers (2)

0___________
0___________

Reputation: 67820

No getting the reference without dereferencing or using it any other way (with some exceptions) is not the Undefined Behaviour.

An example:

int x[5];

printf("%zu\n", sizeof(*(x + 1000));   // no UB

Upvotes: -4

AProgrammer
AProgrammer

Reputation: 52314

&buf[10] is a special case. You can get the address of the "one past last element" of an array without UB. But you can not go further or go before the first element. Thus &buf[11] and &buf[-1] is UB.

Per request, from the latest available draft of C18.

6.5.3.2/3 explains that &buf[10] is equivalent to buf+10:

Similarly, if the operand is the result of a [] operator, neither the & operator nor the unary * that is implied by the [] is evaluated and the result is as if the & operator were removed and the [] operator were changed to a + operator.

and 6.5.6/8 gives us information about the behavior of +:

Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. 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.

Upvotes: 12

Related Questions