Main Content

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.

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 errno for error reporting do not return an error code directly. Instead, they return a special value (such as NULL or -1) that indicates that an error occurred. The programmer must remember to check errno to find out what the error is. If the programmer forgets to check errno, then additional errors can occur.

  • Because errno is a single variable, subsequent function calls that also use errno can overwrite it. This means that if a programmer does not check errno immediately after a function call that sets it, the value can be lost, leading to incorrect error handling.

  • To reliably use errno for error detection, you must reset it to zero before a function call that can set it. errno is not automatically cleared by library functions. If errno already 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

expand all

#include <cstring>
#include <cstdio>

int main() {
    char source[] = "Copy this string";
    char destination[50];
    
    strcpy(destination, source);			//Noncompliant
    
    return 0;
}

In this example, a string is copied by using the strcpy() function, which does not check the size of the destination buffer. If the destination buffer is too small, a buffer overflow can result, leading to undefined behavior.

Check Information

Group: Language support library
Category: Required

Version History

Introduced in R2024b