Result of string::c_str() compared to another
      pointer
The C string obtained from std::string::c_str() is compared to a
      pointer (or NULL)
Since R2021b
Description
This defect occurs when a C string that is obtained by calling the
        std::string::c_str function is compared to a pointer or a NULL. For
      instance, Polyspace® flags the comparison operations in the if statements in this
      code:
void foo(){
	//...
	std::string str{"loren ipsum"};
	//...
	const char pStr[] = "loren ipsum";
	const char* p = str.c_str();
	if(p==NULL){//Defect: Unnecessary
		
	}
	if(p==pStr){ //Defect: Compares pointer address
	//..
	}
	//..
}
Risk
Comparing a pointer to the C string obtained from a string has these risks:
- When you compare the output of - std::string::c_strto a pointer, the addresses of the pointers are compared. You might expect the compiler to compare the content of the pointers. For instance, in the preceding code, you might expect that- (p==pStr)evaluates to- truebecause both pointers contains- loren ipsum. The compiler compares the addresses- pand- pStr, which evaluates to- false. Comparing pointers as a method of comparing strings produces unexpected results.
- The C string - pthat is obtained by calling- std::string::c_str()is always non-NULL. The expression- (p==NULL)always evaluates to- false. Comparing such a C string to NULL might produce unexpected results and indicates a logic error in the code.
Fix
To fix this issue:
- To compare the content of strings, use string functions or use operators with the string objects directly. 
- Because - std::string::c_str()always returns a non-NULL value, remove the comparison to NULL or refactor your logic.
Examples
Result Information
| Group: Programming | 
| Language: C++ | 
| Default: Off | 
| Command-Line Syntax: STD_STRING_C_STR_COMPARED_TO_POINTER | 
| Impact: Low | 
Version History
Introduced in R2021b
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)