by SV_BubbleTime · 5y ago · 0 comments
>In a few places, the original source code contains expressions that point one past the last element of an array. Here is a simplified example of the C code:
int array[1024];
int *p;
if (p >= &array[1024]) {
}
>The C standard (see e.g. C11, Section 6.5.6) allows pointers to an element one past the end of the array.Wait? Why?
I get that char strings in C are null terminated and that might seem like an off by 1 issue if you aren’t paying attention, you still size your string one larger than your string.
What is this all about?
#define COUNT(array) (sizeof(array) / sizeof((array)[0]))
int array[1024];
for (int *p = array; p < array + COUNT(array); ++p) {
// ...
}
For the loop to be well-behaved, such pointer formation must be well-defined.Lots of iterator designs have a special "end" iterator you can compare against but not deference or access - this is just the same for C arrays.
The C standard here allows pointers to elements one past the array, but it's still busted if you try to dereference it.
And it’s interesting to me that Rust doesn’t allow that considering it’s not accessing memory (yet, and that’s the whole point I’m sure.
And the truth is that without runtime memory protection you can dereference those illegal positions.