E
ena8t8si
Robert said:Keith said:Ben C said:Ben C wrote:
[...] a negative subscript to an array will cause undefined
behaviour.
[...] Are you sure?
int x[10];
int *y = x + 5;
y[-1] = 100;
...
y is not an array, it is a pointer.
What about this then?
#include <stdio.h>
int main(void)
{
int x[][3] =
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
printf("%d\n", x[1][-1]);
return 0;
}
x is an array, not a pointer. I believe there is nothing "undefined"
here.
I think that's actually a matter of some dispute.
It might have been in 1992, I think that DR #17 made it pretty clear
that this is undefined behavior. Quote the response to question #16:
"For an array of arrays, the permitted pointer arithmetic in subclause
6.3.6, page 47, lines 12-40 is to be understood by interpreting the use
of the word ``object'' as denoting the specific object determined
directly by the pointer's type and value, not other objects related to
that one by contiguity. Therefore, if an expression exceeds these
permissions, the behavior is undefined. For example, the following code
has undefined behavior:
int a[4][5];
a[1][7] = 0; /* undefined */
Some conforming implementations may choose to diagnose an ``array
bounds violation,'' while others may choose to interpret such attempted
accesses successfully with the ``obvious'' extended semantics."
The result of this question was to add the following to the
(informative) section G.2 which documents examples of undefined
behavior:
"An array subscript is out of range, even if an object is apparently
accessible with the given subscript (as in the lvalue expression
a[1][7] given the declaration int a[4][5]) (6.3.6)."
An easy/lazy/stupid response to the DR, resulting in an
easy/lazy/stupid statement in the standard.
void *v;
int *p;
int a[4][5];
/*1*/ v = &a;
p = (int*)((char*)v + 5 * sizeof(int));
p[7] = 0;
/*2*/ v = &a;
p = (int*)v + 5;
p[7] = 0;
/*3*/ v = a;
p = (int*)v + 5;
p[7] = 0;
/*4*/ p = a[1];
p[7] = 0;
/*5*/ (p = a[1])[7] = 0;
/*6*/ (a[1])[7] = 0;
/*7*/ a[1][7] = 0;
At what point in 1-7 does the behavior become undefined?
Remember, the DR says that "object" means "the specific object
determined directly by the pointer's _type_ and _value_."