Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
}
like image 320
bitsequence35 Avatar asked Mar 03 '23 04:03

bitsequence35


1 Answers

&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.

like image 73
AProgrammer Avatar answered May 10 '23 23:05

AProgrammer