简体   繁体   中英

How to catch exception when write to a random memory block in c++

int main()
{
    int *a; // a = 0x4053c6 (a random address)
    // this will cause the program to exit, and how do i know this memory can't be written ?
    *a = 5;
    return 0;
}

Confused! I mean does this snippet always lead the program to crash ? And is there a case that this program can execute from begin to end?

The code will Segfault / have an access violation which is handled as a trap or a signal depending on the operating system. You may be able to handle it but it is quite unlikely you'll be able to do much afterward. (The usual course of action after handling it is a graceful exit).

As for establishing that there is a case it will be quite tough to prove it. You can have your own compiler that sets uninitialized variables to a particular address on the stack for example (sarcasm).

One way to pseudo-initialize the value in a is to call a function:

void func(int k)
{
    int *a;
    int b = 0;
    if (k == 1) {
        a = &b;
    }
    *a = 5;
}

You can try with func(1) a few times and then try func(2). There is a chance that a and b will reuse the same stack area and not fail. But again this is also a chance .

It will usually lead to a crash, but it's not guaranteed (since the variable is uninitialized, it could contain any value, valid or invalid). You can't catch an access violation with C++ exceptions, but compilers provide extensions to do it. For example, with Visual C++, you can use SEH (Structured Exception Handling):

#include <Windows.h>
#include <iostream>

using namespace std;

int main()
{
    int* p = reinterpret_cast<int*>(0x00000100);

    __try
    {
        *p = 10;
    }
    __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
    {
        cout << "Access violation" << endl;
        return -1;
    }

    cout << *p << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM