Main Content

CWE Rule 597

Use of Wrong Operator in String Comparison

Since R2026a

Description

The product uses the wrong operator when comparing a string, such as using "==" when the .equals() method should be used instead.

Polyspace Implementation

Polyspace checks for the issue Using pointer comparison to compare strings.

Examples

expand all

Issue

This issue occurs when you compare C-style strings by using operators such as == or != on their underlying pointer identifiers. Polyspace® does not report a violation if you compare the underlying pointer of a C-style string with 0 to check for null pointers.

Risk

Comparing underlying pointers checks if two pointers point to the same address. Such checks do not compare the actual content of two strings. Using pointer comparison instead of string comparison is a logic error and can result in unexpected behavior.

Fix

Compare C-style strings with string comparison functions such as strcmp or strncmp. Alternatively, In C++, use std::string and its associated functions and operators.

Example

In this example, two C-style string pointers are compared with ==, which compares addresses rather than the contents of the strings.

void compareStrings() {
    const char* str1 = "Hello";
    const char* str2 = "Hello";
    if (str1 == str2) { // Noncompliant
        // ...
    }
}
Correction

Use std::strcmp for comparing C style strings.

#include <cstring>
#include <string>

void compareStrings_correct() {
    const char* str1 = "Hello";
    const char* str2 = "Hello";
    if (std::strcmp(str1, str2) == 0) { // Compliant
        // ...
    }

    std::string s1 = "Hello";
    std::string s2 = "Hello";
    if (s1 == s2) { // Compliant
        // ...
    }
}

Check Information

Category: Others
PQL Name: std.cwe_native.R597

Version History

Introduced in R2026a