C++: preventing buffer overflows with bounds checks
Many serious security flaws are memory-safety bugs. A buffer overflow writes past the end of an array and can overwrite neighbouring data or return addresses. Reading past the end can leak secrets. In C++ the operator[] on arrays and vectors does no checking, so the program must check sizes itself.
C++
#include <cstddef>
#include <cstring>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
bool copy_name(const std::string& input, char* out, std::size_t capacity) {
if (input.size() + 1 > capacity) {
return false;
}
std::memcpy(out, input.c_str(), input.size() + 1);
return true;
}
int main() {
char buffer[8];
std::cout << copy_name("Ada", buffer, sizeof buffer) << " " << buffer << "\n";
std::cout << copy_name("Programonic", buffer, sizeof buffer) << " " << buffer << "\n";
std::vector<int> scores = {82, 91, 76};
try {
std::cout << scores.at(1) << "\n";
std::cout << scores.at(7) << "\n";
} catch (const std::out_of_range&) {
std::cout << "index 7 rejected\n";
}
}