Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C negative array index

this is my struct :

struct Node {
    struct Node* data;
    struct Node* links[4];
}

assuming there is no padding, does Node->links[-1] guaranteed to be pointing on Node::data ?

like image 414
uray Avatar asked Oct 24 '10 00:10

uray


2 Answers

No guarantee; this is undefined behaviour:

  • Compiler-dependent structure padding
  • Standard only defines array indexing between 0 and length (inclusive)
  • Possible strict-aliasing violation

In practice, it's quite possible that you will end up pointing at data, but any attempts to access it will result in UB.

like image 63
Oliver Charlesworth Avatar answered Sep 30 '22 01:09

Oliver Charlesworth


Array subscripting is defined in terms of pointer arithmetic, and the C99 standard has this to say about pointer arithmetic:

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 accessing Node->links[-1] (even just getting the address of Node->links[-1]) is undefined behavior, strictly speaking. So you have no guarantee that Node->links[-1] will get you Node::data.

But as many commentators mention, it will work pretty much always. I'd still consider it poor programming practice that should be avoided. If not for the technicality, then because it requires that modifications to struct Node can easily cause bugs that the compiler will not help you with. When someone adds something between data and links, things will mysteriously break.

like image 42
Michael Burr Avatar answered Sep 30 '22 01:09

Michael Burr