Catch a Memory Access Violation in C++
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
:
#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.
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, 2022Comments
-
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 almost 11 yearsIs 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 almost 11 years@rsethc That seems reasonably workable if they are two different processes.
-
Admin almost 11 yearsI 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 about 7 yearsHow can I know whether or not my project is MSVC?
-
user3046442 almost 3 yearsIf you create a project using Visual studio then it is compiled with MSVC.