MISRA C++:2023 Rule 21.2.2
The string handling functions from <cstring>,
<cstdlib>, <cwchar> and
<cinttypes> shall not be used
Since R2024b
Description
Rule Definition
The string handling functions from <cstring>,
<cstdlib>, <cwchar> and
<cinttypes> shall not be used. 1
Rationale
Using C-style string handling functions can lead to out-of-bounds read or write operations because these functions do not perform automatic bounds checking. Such memory access violations can lead to issues such as data corruption, program crashes, and security vulnerabilities. To avoid these issues, use modern C++ features that manage memory safely and provide bounds-checking operations.
Additionally, certain string handling functions report errors using
errno, which can also cause issues. For example:
Functions that use
errnofor error reporting do not return an error code directly. Instead, they return a special value (such asNULLor-1) that indicates that an error occurred. The programmer must remember to checkerrnoto find out what the error is. If the programmer forgets to checkerrno, then additional errors can occur.Because
errnois a single variable, subsequent function calls that also useerrnocan overwrite it. This means that if a programmer does not checkerrnoimmediately after a function call that sets it, the value can be lost, leading to incorrect error handling.To reliably use
errnofor error detection, you must reset it to zero before a function call that can set it.errnois not automatically cleared by library functions. Iferrnoalready contains an error code from a previous unrelated operation, it can falsely indicate that an error occurred when no error occurred.
You can achieve results provided by C-style string functions using C++ standard library features that are more reliable and less error prone.
Polyspace Implementation
The rule checker reports a violation whenever the code uses a string handling function
from <cstring>, <cstdlib>,
<cwchar>, and <cinttypes>, including
functions that use errno. For a full list of functions, see the MISRA
documentation.
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: Language support library |
| Category: Required |
Version History
Introduced in R2024b
1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.