This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 21.2.2 - The string handling functions from <cstring>, <cstdlib>, <cwchar>
and <cinttypes> shall not be used
[cstring.syn]
[cerrno.syn]
[C11] / 7.1.4; Undefined 1
[C11] / 7.24.1; Undefined 1
[C11] / 7.29.4; Undefined 1
Category: Required
Analysis: Decidable, Single Translation Unit
Amplification
The string handling functions are:
From <cstring> |
strcat strchr strcmp strcoll strcpy strcspn strerror strlen strncat strncmp strncpy strpbrk
strrchr strspn strstr strtok strxfrm |
From <cstdlib> |
strtol strtoll strtoul strtoull strtod strtof strtold |
From <cwchar> |
fgetwc fputwc wcstol wcstoll wcstoul wcstoull wcstod wcstof wcstold |
From <cinttypes> |
strtoumax strtoimax wcstoumax wcstoimax
|
These functions shall not be called or have their addresses taken, and no macro having one of these names shall be expanded.
Note: the same functions from <string.h>, <stdlib.h>, <wchar.h> and
<inttypes.h> are also covered by this rule.
Rationale
Incorrect use of some string handling function may result in a read or write access beyond the bounds of an object passed as a parameter,
resulting in undefined behaviour. Also, some string handling functions only report errors through the use of errno,
which is a fragile mechanism — a non-zero value may reveal an error in any function that was called between the last point the value 0
was assigned to errno and the current point.
In all cases, the features provided by these functions can be obtained through other C++ Standard Library features which are less error-prone.
Example
void f1( char * buffer, size_t bufferSize )
{
char const * str = "Msg";
if ( ( strlen( str ) + 1u ) < bufferSize ) // Non-compliant
{
( void ) strcpy( buffer, str ); // Non-compliant
}
}
The following example performs the same operations in a compliant way:
void f2( char * buffer, size_t bufferSize )
{
std::string_view str = "Msg";
if ( str.size() + 1u < bufferSize )
{
str.copy( buffer, str.size() );
buffer[ str.size() ] = 0;
}
}
Copyright The MISRA Consortium Limited © 2023