1 #include <stdexcept>
2 #include <iostream>
3 #include <array>
4 
5 #include <boost/safe_numerics/safe_integer_range.hpp>
6 
detected_msg(bool detected)7 void detected_msg(bool detected){
8     std::cout << (detected ? "error detected!" : "error NOT detected! ") << std::endl;
9 }
10 
main(int,const char * [])11 int main(int, const char *[]){
12     // problem: array index values can exceed array bounds
13     std::cout << "example 5: ";
14     std::cout << "array index values can exceed array bounds" << std::endl;
15     std::cout << "Not using safe numerics" << std::endl;
16     std::array<int, 37> i_array;
17 
18     // unsigned int i_index = 43;
19     // the following corrupts memory.
20     // This may or may not be detected at run time.
21     // i_array[i_index] = 84; // comment this out so it can be tested!
22     std::cout << "error NOT detected!" << std::endl;
23 
24     // solution: replace unsigned array index with safe_unsigned_range
25     std::cout << "Using safe numerics" << std::endl;
26     try{
27         using namespace boost::safe_numerics;
28         using i_index_t = safe_unsigned_range<0, i_array.size() - 1>;
29         i_index_t i_index;
30         i_index = 36; // this works fine
31         i_array[i_index] = 84;
32         i_index = 43; // throw exception here!
33         std::cout << "error NOT detected!" << std::endl; // so we never arrive here
34     }
35     catch(const std::exception & e){
36         std::cout <<  "error detected:" << e.what() << std::endl;
37     }
38     return 0;
39 }
40