I am working with image and video manipulation and in a few cases really do need unsafe code for speed purposes. Sometimes I use code something like the following:
var data = new byte[n];
fixed (byte* fixData = data)
{
byte* ptrData = &fixData[0];
for (int i = 0; i < n; i++)
{
*(ptrData++) = 42;
}
}
My question is, since ptrData
is incremented n
times, it ends up pointing outside the array, but is this a problem? It is never assigned anything of course, since the increment happens after the last value-assignment, but could this code still break something, and if so, how serious? I have run code like this 1_000s of times and never encountered a problem, but still?
That code isn't unsafe. The only issue is a failed allocation of data
. Since n
is always the length of data
there's no way for someone to move i
out of bounds to write - your loop is only dependent on the value of n
.
At the end of the loop i >= n
which would produce an out-of-bounds write if you were to write data. Therefore you must ask yourself: is it possible that your program could be influenced to write an extra value at the end? If yes, your data is unsafe. If no, you're fine.
The issue that causes buffer overflows isn't that the index surpasses the length; the issue is that the code continues writing once that happens. You enter a state where i >= n
but that's merely the state after the loop is over. i
could be any possible value and you'd have no reason to care since you're not using the value anymore.