Home >Backend Development >C++ >How Can I Catch Memory Access Violation Exceptions in Standard C ?

How Can I Catch Memory Access Violation Exceptions in Standard C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 13:14:14440browse

How Can I Catch Memory Access Violation Exceptions in Standard C  ?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn