Questionable instance of C code, in which a negative number is used to index an array. For example:
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:
*(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
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
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
] to put
] into a writeup without linking. That might be intuitively obvious to some, but not to everybody...