Can Interlocked.Increment overflow cause .NET runtime corruption?
Asked Answered
S

1

12

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)?

Spheroid answered 22/2, 2016 at 16:29 Comment(5)
In this context, location is simply the name of an int variable. So saying location + 1 is just a normal mathematical statement.Anthea
location + 1 is just a mathematical statement. location = Int32.MaxValue so location + 1 would overflow to Int32.MinValueTailrace
Yes, that makes more sense. (I've been reading too much pointer arithmetic.) Thanks to all for the clarification!Spheroid
It is a pretty uninspired name, the argument is actually a pointer. Thus "location". The ref keyword in C# ensures that a pointer is generated at runtime. The jitter directly translates the method to a single CPU instruction, LOCK XADD for x86 and x64, no runtime corruption can occur.Saloop
I guess the name threw me off, along with the use of = to represent equality rather than assignment. I figured that I was probably missing something obvious.Spheroid
C
12

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);
Casimiracasimire answered 22/2, 2016 at 16:36 Comment(1)
Just to mention that value = checked(Interlocked.Increment(ref value)); does not throw an exception if value is int.MaxValue, it just sets it to int.MinValueCentrobaric

© 2022 - 2024 — McMap. All rights reserved.