Modern C++ to the rescue
Let’s revisit the preceding examples but replace the naked arrays and naked pointers with their STL equivalents, as recommended in modern C++.
First, the array bounds example. We simply replace the naked array with a vector<int>
instance and we get the following function:
int doSomeWork(int value1, int value2, int value3, int value4) { vector<int> values; values[0] = value1; values[1] = value2; values[3] = value3; values[4] = value4; return values[0] + values[1] + values[3] + values[4]; } TEST_CASE("try vector bounds"){ int result = doSomeWork(1, 234, 543, 23423); CHECK_EQ(1 + 234 + 543 + 23423, result); }
Unfortunately, the result of running this example is not great. Neither g++
nor clang
complains, and we get the following result when running the test:
TEST CASE: try vector bounds test.cpp:5: FATAL ERROR: test case CRASHED: SIGSEGV - Segmentation violation signal
Is std::vector<>
unsafe? Well, we...