Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch a Memory Access Violation in C++

In C++, is there a standard way (or any other way, for that matter) to catch an exception triggered by a memory access violation?

For example, if something went wrong and the program tried to access something that it wasn't supposed to, how would you get an error message to appear saying "Memory Access Violation!" instead of just terminating the process and not showing the user any information about the crash?

I'm programming a game for Windows using MinGW, if that helps any.

like image 304
rsethc Avatar asked May 17 '13 15:05

rsethc


2 Answers

Access violation is a hardware exception and cannot be caught by a standard try...catch.

Since the handling of hardware-exception are system specific, any solution to catch it inside the code would also be system specific.

On Unix/Linux you could use a SignalHandler to do catch the SIGSEGV signal.

On Windows you could catch these structured exception using the __try/__except statement.

like image 177
zakinster Avatar answered Oct 07 '22 18:10

zakinster


This doesn't quite help you, but access violations and other SEH exceptions can be caught in MSVC using try...catch(...), if you compile with /EHa:

MSVC Yes with SEH exceptions (/EHa)

Live demo

#include <iostream>
int main() {
  try {
    *(int*)0 = 0;
  }
  catch (...) {
    std::cerr << "Exception!\n";
  }
}

Output:

Exception!

The only downside is you have no way of knowing what went wrong. To know more about the exception you can set a custom SEH translator function with _set_se_translator like in this article.

like image 26
rustyx Avatar answered Oct 07 '22 18:10

rustyx