C-style strings shall not be used
C-style strings shall not be used.
The underlying character array that stores a C-style string has many disadvantages such as:
You must explicitly handle memory allocation and deallocation if you perform operations on the string that require non-trivial memory manipulations.
It is not always clear whether a char* points to a single
character or to a C-style string.
You might accidentally convert an array to a raw pointer when you pass it by value
or by pointer to a function, which results in a loss of information about the array
size (array decay). For example, in this code snippet, func prints
the size of the pointer to the first character of cString (8) ,
while the actual size of cString is
6.
void func(char *c){ //function takes array by value
cout << sizeof(c);
}
void main(){
char cString[]{ "pizza" }; //Size is 6 (5 characters + null terminator)
func(cString); // Size is 8 (size of char*)
}
Instead, use the std::string class to store a sequence of
characters. The class handles allocations and deallocations, and instantiates an object
that you can safely pass to functions. The class also has built-in functionalities to
manipulate the string such as iterators.
Polyspace® flags the use of:
Pointers to char (char*) and arrays of char (char
someArray[]).
Pointers to and arrays of char with a type qualifier such as
volatile or const. For example char
const*.
Pointers to and arrays of type wchar_t,
char16_t, and char32_t.
If you have a function declaration and its definition in your source code, Polyspace places the violation on the function definition. For example:
const char* greeter(void);
//....
const char* greeter(void){ //Non-compliant
return "Hello";
}Polyspace does not flag the use of:
Pointers to or arrays of signed or unsigned
char. For example, signed_c and unsigned_arr are
not flagged in this code
snippet:
signed char* signed_c; unsigned char unsigned_arr[2048];
Literal strings. For example, the return value of greeter() is
not flagged in this code snippet, but the use of const char* in the
first line is
flagged:
const char* greeter(void){ //Non-compliant
return "Hello"; // Compliant
}The parameters of main().
If you expect a rule violation but do not see it, refer to the documentation for Polyspace Bug Finder™ or Polyspace Bug Finder Server™.
| Group: Input/output library |
| Category: Required, Automated |