-1

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?

MinosIllyrien
  • 330
  • 1
  • 9
  • There are no architectures in common use today that can fail this code. Taken advantage of particularly in C++, an iterator's end() function need to spit out a usable value that can be compared for the end-condition. Which by itself would prevent anybody from creating such an architecture, great loss. The one thing you can't do is de-reference such a pointer, not a problem here. – Hans Passant Sep 04 '20 at 23:11

1 Answers1

3

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.

Serpent27
  • 332
  • 2
  • 7
  • 2
    Note that this snippet isn't "unsafe" in the way a C++ developer might use the term, but it is "unsafe" in the way C# uses the term. Writing this code would require using the `unsafe` keyword and adding the -unsafe compiler flag to "allow unsafe code". The point is that unsafe doesn't mean insecure or broken it means "not guaranteed to be safe by the system". – Mike Zboray Sep 04 '20 at 20:55