...
Because the input is unbounded, the following code could lead to a buffer overflow:.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <iostream> void f() { char buf[12]; std::cin >> buf; } |
...
To solve this problem, it may be tempting to use the std::ios_base::width()
method, but there still is a trap, as shown in this noncompliant code example:.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <iostream> void f() { char bufOne[12]; char bufTwo[12]; std::cin.width(12); std::cin >> bufOne; std::cin >> bufTwo; } |
In this example, the first read will not overflow, but could fill bufOne
with a truncated string. Furthermore, the second read still could overflow bufTwo
. The C++ Standard, [istream.extractors], paragraphs 7–9, describes the behavior of operator>>(basic_istream &, charT *)
and, and states in part [ISO/IEC 14882-2014], states the following:
operator>>
then stores a null byte (charT()
) in the next position, which may be the first position if no characters were extracted.operator>>
then callswidth(0)
.
...
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; } |
...