I'm trying to find out if this scenario that caused an OverflowException could possibly be something that could be caught by static code analysis.
//IntPtr position = ...
position = (IntPtr) ((int) position + stride);
The above code employs incorrect casting of an IntPtr to a 32-bit number (instead of 64-bit number), which results in an OverflowException when a memory pointer has a 64-bit address. This only happens on a 64-bit version of Windows.
position = (IntPtr) ((long) position + stride);
And here is the fix, casting the IntPtr to a long instead.
It seems to me like something like this could have been caught by static code analysis. However, even running code analysis with Microsoft All Rules returns no findings on this code.
Is there a reason why something like this wasn't raised as a finding? Or is there a ruleset that might have caught it?
IntPtris designed to work both on 32-bit and 64-bit systems. To that end, it has constructor overloads that takeInt32andInt64parameters.You can avoid this problem altogether by using
IntPtr.Addmethod: