Catch a Memory Access Violation in C++

16,445

Solution 1

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.

Solution 2

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.

Share:
16,445
rsethc
Author by

rsethc

Sometimes I write code as an employee, but I'm often working on my own projects on my own time as a hobbyist. Lately I've been spending a lot of time trying to make a scripting language interpreter: https://gitlab.com/rsethc/jank

Updated on June 14, 2022

Comments

  • rsethc
    rsethc almost 2 years

    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.

  • rsethc
    rsethc almost 11 years
    Is it possible to have a 'main' process that launches the actual app and then shows the error message based on the return code from the crashed app process?
  • zakinster
    zakinster almost 11 years
    @rsethc That seems reasonably workable if they are two different processes.
  • Admin
    Admin almost 11 years
    I think it might also be worth mentioning that there are systems without MMU (or MPU) that cannot detect a memory access violation at all.
  • Dominique
    Dominique about 7 years
    How can I know whether or not my project is MSVC?
  • user3046442
    user3046442 almost 3 years
    If you create a project using Visual studio then it is compiled with MSVC.