Fix S2589 FP: Unsigned number doubling by adding with itself inside while loop
Opened this issue · 1 comments
MineCake147E commented
Description
S2589 is being reported when using unsigned x += x
.
Repro steps
public static void UIntPtrS2589FalsePositive()
{
nuint u = 1;
while (u > 0) // noncompliant FP
{
u += u; // this addition could overflow to 0
}
}
public static void UInt64S2589FalsePositive()
{
ulong u = 1;
while (u > 0) // noncompliant FP
{
u += u; // this addition could overflow to 0
}
}
public static void UInt32S2589FalsePositive()
{
uint u = 1;
while (u > 0) // noncompliant FP
{
u += u; // this addition could overflow to 0
}
}
Expected behavior
No issue should be found.
Actual behavior
u > 0
gets S2589
Known workarounds
Use either u *= 2;
or u <<= 1;
instead of u += u;
.
Related information
- SonarLint for Visual Studio 2022 7.8.0.88494
- Microsoft Visual Studio Community 2022 (64-bit) - Preview Version 17.10.0 Preview 4.0
- dotnet 8.0.300-preview.24203.14
- Operating System: Windows 11 Home 22H2 22621.3447
martin-strecker-sonarsource commented
Hello @MineCake147E, thank you for bringing this issue to our attention. Upon investigation, I can confirm that it is a false positive. I have added a reproducer in #9192 to document this. S2589 is designed not to consider overflows intentionally (otherwise, we would miss a lot of true positives).
However, we should respect unchecked
statements/expressions. By adding unchecked
in your examples, the code becomes clearer and more intentional.
Unfortunately, we are not taking unchecked
into account yet, but I have added this issue to our backlog for future implementation.