mirror of
https://github.com/boostorg/safe_numerics.git
synced 2026-02-17 14:02:14 +00:00
first version with working policies
promotion pollicy exception policy improved documentation
This commit is contained in:
40
examples/example5.cpp
Normal file
40
examples/example5.cpp
Normal file
@@ -0,0 +1,40 @@
|
||||
#include <cassert>
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
|
||||
#include "../include/safe_range.hpp"
|
||||
|
||||
void detected_msg(bool detected){
|
||||
std::cout << (detected ? "error detected!" : "error NOT detected! ") << std::endl;
|
||||
}
|
||||
|
||||
int main(int argc, const char * argv[]){
|
||||
// problem: array index values can exceed array bounds
|
||||
std::cout << "example 5: ";
|
||||
std::cout << "array index values can exceed array bounds" << std::endl;
|
||||
std::cout << "Not using safe numerics" << std::endl;
|
||||
int i_array[37];
|
||||
|
||||
unsigned int i_index = 43;
|
||||
// the following corrupts memory.
|
||||
// This may or may not be detected at run time.
|
||||
// i_array[i_index] = 84; // comment this out so it can be tested!
|
||||
detected_msg(false);
|
||||
|
||||
// solution: replace unsigned array index with safe_unsigned_range
|
||||
std::cout << "Using safe numerics" << std::endl;
|
||||
try{
|
||||
using namespace boost::numeric;
|
||||
safe_unsigned_range<0, sizeof(i_array)/sizeof(int) - 1> i_index;
|
||||
i_index = 36; // this works fine
|
||||
i_array[i_index] = 84;
|
||||
i_index = 37; // throw exception here!
|
||||
i_array[i_index] = 84; // so we never arrive here
|
||||
assert(false);
|
||||
}
|
||||
catch(std::range_error & e){
|
||||
std::cout << e.what() << std::endl;
|
||||
detected_msg(true);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user