AUTOSAR C++14 Rule A27-0-4
Description
Rule Definition
C-style strings shall not be used.
Rationale
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 ofcString
(8) , while the actual size ofcString
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 Implementation
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
orconst
. For examplechar const*
.Pointers to and arrays of type
wchar_t
,char16_t
, andchar32_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
orunsigned
char. For example,signed_c
andunsigned_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 ofconst char*
in the first line is flagged:const char* greeter(void){ //Non-compliant return "Hello"; // Compliant }
The parameters of
main()
.
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Input/output library |
Category: Required, Automated |
Version History
Introduced in R2021a