5 ms·
They might call the example something other than "SafeSum" as it produces wrong answers on overflow :)
by fulafel 9y ago
They might call the example something other than "SafeSum" as it produces wrong answers on overflow :)
- int_19h 9y agoNot if you compile with -checked+ - then it throws. Although the right way to do this is to use a checked-block: checked { sum += bytes[i]; } It's one obscure C# feature that I rarely see used, but which I find indispensable, and really wish more languages adopted it. Integer overflow vulnerabilities have become more prominent in the past few years, so perhaps there will be some uptake. Interestingly, C# had this feature since the very first release back in 2001.
- wtetzner 9y agoIt would be even better if checked was the default, and you had to use an unchecked block to get unchecked arithmetic.
- benaadams 9y agoCan set it at the project level; then you need to use unchecked instead: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/checked-and-unchecked https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...
- benaadams 9y agoCan't overflow? Is a Span of byte (0-255) being added to a ulong(0-1.8e+19) The maximum value it can produce is much less than a ulong: 2^31 * 255 = 547608330240
- fulafel 9y agoAre Spans limited to 32 bits then?