Questionable instance of C code, in which a negative number is used to index an array. For example:

char st[5];
st[-1] = 0;

This code looks at the memory address that st is located at, backs up one byte (assuming you're on a system with one-byte characters), and writes the value 0 to it. Since array indexing is another syntax for dereferencing pointer arithmetic, the code is functionally equivalent to:

char st[5];
*(st-1) = 0;

In the above example, there is no way to determine what is stored in memory directly before st; the code might run flawlessly, it may overwrite some arbitrary variable, or it may crash with a Segmentation Fault.

There are occasional instances where negative indexing could come in handy. If a pointer p points to the nth element of an array, then p[-m] (where m is a positive integer) refers to the element m places before the one the pointer refers to. Extreme care must be taken, however, to ensure that m < n at all times.


Why did I node this? The Frankensteinian project I'm debugging for work right now has fifty-six instances of negative pointer indexing.

I feel I should draw attention to Cabaal's tiny but helpful writeup for brackets, which recommends the use of &#91; and &#93; to put [ or ] into a writeup without linking. That might be intuitively obvious to some, but not to everybody...