...
Code Block |
---|
|
#include <iostream>
void f() {
char buf_onebufOne[12];
char buf_twobufTwo[12];
std::cin.width(12);
std::cin >> buf_onebufOne;
std::cin >> buf_twobufTwo;
} |
Noncompliant Code Example
...
Code Block |
---|
|
#include <iostream>
void f() {
char buf_onebufOne[12];
char buf_twobufTwo[12];
std::cin.width(12);
std::cin >> buf_onebufOne;
std::cin.width(12);
std::cin >> buf_twobufTwo;
} |
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 string_onestringOne, string_twostringTwo;
std::cin >> string_onestringOne >> string_twostringTwo;
} |
Noncompliant Code Example
...
Code Block |
---|
|
#include <fstream>
#include <string>
void f(std::istream &in) {
char buffer[32];
try {
in.read(buffer, 32);
} catch (std::ios_base::failure &Ee) {
// Handle error
}
std::string str(buffer);
// ...
} |
...
Code Block |
---|
|
#include <fstream>
#include <string>
void f(std::istream &in) {
char buffer[32];
try {
in.read(buffer, 32);
} catch (std::ios_base::failure &Ee) {
// Handle error
}
std::string str(buffer, 32);
// ...
} |
...