int arr[ 5 ] = { 0 };
int i = 8; // out of bounds
arr[ i ] = 8;
I know that I can just check i like this if( i < 0 || i > 5 ) ….
I also know about SEH in Visual Studio, but it looks like not working solution.
__try { /* code */ }
__except(GetExceptionCode() == EXCEPTION_ARRAY_BOUNDS_EXCEEDED)
This is not working. As I see SEH working in situations like divide to 0, access protected pages … How can I protect my program from crashes?
There is no guarantee that SEH will catch this – it depends on your hardware detecting the access , which does not happen for all invalid array accesses. If you want to be sure of catching it, use the standard C++
std::vectorcontainer instead of an array, and access it via itsat()member function, rather than the[]operator – this will raise a standard C++ exception if the access is invalid.