Catching Memory Access Violation Exceptions in Standard C
Standard C offers limited support for catching memory access violation exceptions without resorting to Microsoft-specific extensions.
Example:
Consider the code:
int *ptr; *ptr = 1000;
Attempting to dereference an uninitialized pointer would normally lead to an access violation exception. However, standard C does not provide a dedicated mechanism to handle such exceptions.
Solution:
The trick lies in throwing a custom exception within the signal handler and catching it outside. Here's the implementation:
#include <signal.h> void SignalHandler(int signal) { printf("Signal %d", signal); throw "!Access Violation!"; } int main() { signal(SIGSEGV, SignalHandler); try { *(int *) 0 = 0; // Trigger access violation (intentionally bad code) } catch (const char *e) { printf("Exception Caught: %s\n", e); } printf("Execution continues... (Note: Bad coding practices should be avoided)"); }
When an access violation occurs, the custom exception is thrown and caught outside the signal handler. This allows for custom exception handling without relying on Microsoft-specific extensions.
The above is the detailed content of How Can I Catch Memory Access Violation Exceptions in Standard C ?. For more information, please follow other related articles on the PHP Chinese website!