cpp:S3519 false positive with std::toupper in a string loop

Product: SonarQube Server 2025.4.4.119049
C++ analyzer: 6.70.1 (build 93088)
Language: C++
Rule: cpp:S3519

SonarQube reports this message on the loop:
“Access of the string literal at index 1, while it holds only a single ‘char’ element”

Minimal example:

int compareCaseInsensitive(const char* left, const char* right)
{
    if (left == nullptr) left = "";
    if (right == nullptr) right = "";

    while (std::toupper(*left) == std::toupper(*right))
    {
        ++left;
        ++right;
        if ('\0' == left[-1]) return 0;
    }

    return std::toupper(*left) - std::toupper(*right);
}

I upload a screenshot (even if you do not like them ;)) so you can follow SQ argumentation without needing to reproduce:

This is a clear false positive.
If we enter the loop, left and right are identical (5) and “” (because 3), therefore 7 can never be false.

My understanding is that SQ treats std::toupper() as unknown. It does not know it is basically a noop on ‘\0’. Therefore it does not know both arrays are identical.

Explicitly checking both current characters before advancing makes the finding disappear:

        ++left;
        ++right;
        if ('\0' == left[-1] || '\0' == right[-1]) return 0;

No idea if you can fix that, but it stays a false positive.

Hi @KUGA2 !

Indeed it is a false positive. It occurs because of our analyzer modelling std::toupper behavior too conservatively. It treats it as any other opaque function assuming no relation between its input and output and assuming its output can be different for the same input.

Here is a shorter and more obvious showcase of the same limitation:

int toUpperLimitation(const char c) {
    if (std::toupper(c) != '\0') return 0;
    if (std::toupper(c) == '\0') return 0;
    return 1 / 0; // False Positive: div-by0
}

Compiler Explorer

I added this limitation to our backlog. Thank you!

did not know you can reproduce in godbolt. Thats good to know for future reports :slight_smile: