You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
LGTM.com - false positive in [cpp/constant-comparison] #4249
Description states "Comparison is always false because n >= 0" but n is returned from Snprintf, which gets it from Vsnprintf(), which gets it from vsnprintf() which may return a negative number in the case of an error (C++ stdio, GlibC, and MSDN docs confirm). Why does LGTM think n must be positive?
Thanks for the report. I believe the alert is correct even if it's rather confusing.
When n is a signed int and you check n >= sizeof(buf), you're comparing a signed left-hand side to an unsigned right-hand side of a wider type. In this case, the compiler inserts a cast to make the left-hand side unsigned before comparing. If n is negative, it becomes a very large positive number, and so n >= sizeof(buf) is true and the n < 0 check is skipped.
It would be safe to remove the n < 0 check, but I definitely understand if you want to keep it for the sake of readers and future maintainers. As a workaround, you can make the alert go away by swapping the order of the operands to ||.
Activity
jbj commentedon Sep 11, 2020
Thanks for the report. I believe the alert is correct even if it's rather confusing.
When
nis a signedintand you checkn >= sizeof(buf), you're comparing a signed left-hand side to an unsigned right-hand side of a wider type. In this case, the compiler inserts a cast to make the left-hand side unsigned before comparing. Ifnis negative, it becomes a very large positive number, and son >= sizeof(buf)is true and then < 0check is skipped.It would be safe to remove the
n < 0check, but I definitely understand if you want to keep it for the sake of readers and future maintainers. As a workaround, you can make the alert go away by swapping the order of the operands to||.Silence static analysis warning
stef (#1)