...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <iostream> #include <string> void f() { std::string input; std::string string_one, string_two; std::cin >> string_one >> string_two; } |
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 of of the std::string
constructor results in undefined behavior if the character array does not contain a null terminator.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <fstream>
#include <string>
void f(std::istream &in) {
char buffer[32];
try {
in.read(buffer, 32);
} catch (std::ios_base::failure &E) {
// Handle error
}
std::string str(buffer);
// ...
} |
Compliant Solution
This compliant solution continues to assume that the input from the file is exactly 32 characters and instead of inserting a null terminator, it constructs the std::string
object based on the size. If the size of the input is uncertain, it is better to use std::basic_istream<T>::readsome()
or a formatted input function, depending on need.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <fstream>
#include <string>
void f(std::istream &in) {
char buffer[32];
try {
in.read(buffer, 32);
} catch (std::ios_base::failure &E) {
// Handle error
}
std::string str(buffer, 32);
// ...
} |
Risk Assessment
Copying string data to a buffer that is too small to hold that data results in a buffer overflow. Attackers can exploit this condition to execute arbitrary code with the permissions of the vulnerable process.
...
[ISO/IEC 14882-2014] | 27.7.2.2.3, " |
[Seacord 2013b] | Chapter 2, "Strings" |
...