Copying data to a buffer that is not large enough to hold that data results in a buffer overflow. Buffer overflows occur frequently when manipulating strings [Seacord 2013]. To prevent such errors, either limit copies through truncation or, preferably, ensure that the destination is of sufficient size to hold the data to be copied. C-style strings require a null character to indicate the end of the string, while the C++ std::basic_string
template requires no such character. This rule is a C++-specific instance of STR31-C. Guarantee that storage for strings has sufficient space for character data and the null terminator.
Noncompliant Code Example
...
Consequently, it is necessary to call width()
prior to each operator>>
call passing a bounded array.
Noncompliant Code Example
The following noncompliant code example calls std::ios_base_width()
prior to each call to operator>>()
. However, it still this does not account for the input being truncated. Only the first 11 characters are read from the standard input stream, and a null terminator is then appended. The input could therefore be truncated, leading truncated, which may lead to information loss or a possible vulnerability.
...
bgColor | #ffcccc |
---|---|
lang | cpp |
...
.
...
Compliant Solution
The best solution for ensuring that data is not truncated and for guarding against buffer overflows is to use std::string
instead of a bounded array, as in this compliant solution:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <iostream> #include <string> void f() { std::string input; std::string stringOne, stringTwo; std::cin >> stringOne >> stringTwo; } |
Noncompliant Code Example
In this noncompliant example, the unformatted input function std::basic_istream<T>::read()
is used to read an unformatted character array of 32 characters from the given file. However, the read()
function does not guarantee that the string will be null terminated, so the subsequent call of the std::string
constructor results in undefined behavior if the character array does not contain a null terminator.
...