rsethc
rsethc

Reputation: 2694

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.

Upvotes: 7

Views: 19587

Answers (2)

rustyx
rustyx

Reputation: 85541

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.

Upvotes: 5

zakinster
zakinster

Reputation: 10698

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.

Upvotes: 12

Related Questions