example5.cpp 1.4 KB

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