Search code examples
c#.netoverflowinterlocked

Can Interlocked.Increment overflow cause .NET runtime corruption?


The MSDN documentation for Interlocked.Increment states:

This method handles an overflow condition by wrapping: if location = Int32.MaxValue, location + 1 = Int32.MinValue. No exception is thrown.

What does “location + 1” mean in this context? If Increment alters the memory location next to the location field, isn't this likely to lead to corruption in the .NET runtime, given that this adjacent location could be anything (object references, class metadata, etc)?


Solution

  • It just means that if your value you want to increment is already equal to Int32.MaxValue and you increment by one, instead of throwing an error, it returns Int32.MinValue

    That's the same what happens if you do

    var value = Int32.MaxValue;
    value += 1;
    

    If you explicitly want an exception to be thrown, use the checked keyword

    var value = Int32.MaxValue;
    value = checked(value + 1);