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