2

Consider this code:

try
{
    int* test = (int*)0x00000001;
    *test = 232;
}
catch(...)
{
}

I am getting a Access violation writing location 0x00000001. Is it possible to catch this in a simple way, or avoid my program crashing in an unpleasant way?

Pacha
  • 1,438
  • 3
  • 23
  • 46
  • 1
    The answer is OS dependent. What OS is this code for? – tohava Jul 28 '13 at 23:04
  • @tohava Windows and Linux – Pacha Jul 28 '13 at 23:04
  • 4
    exceptions are not a way to avoid fixing bugs in your code – aaronman Jul 28 '13 at 23:05
  • 2
    @aaronman It isn't a bug in my code, I am using a external .dll that returns invalid memory locations most of the time. I wrote that snipped to represent my problem – Pacha Jul 28 '13 at 23:05
  • Sounds like a really bad dll then – aaronman Jul 28 '13 at 23:06
  • @pacha are you sure it's the DLL and not just you using the wrong calling convention or otherwise using the DLL incorrectly? Or perhaps a 32/64-bit incompatibility... – paddy Jul 28 '13 at 23:07
  • @paddy No, this .dll was made by someone who works with me on a protocol he made. I asked him and he said that might happend and he lost the code, so I am stuck with it – Pacha Jul 28 '13 at 23:08
  • 1
    @Pacha - in Linux, you can set a signal handler via `sigaction`. There is no portable way for both. – tohava Jul 28 '13 at 23:09
  • Write a separate program that mediates access to the buggy library and be prepared to restart it when it crashes. – Casey Jul 28 '13 at 23:11
  • 3
    Alternatively, convince your manager that this is your colleague's problem to fix and not yours. – Casey Jul 28 '13 at 23:12
  • 1
    @Pacha Sounds like this colleague should either find and fix the code, rewrite the DLL correctly, or look for a new job. The code should have been in source control and backed up in multiple locations. – paddy Jul 28 '13 at 23:26
  • How exactly would you propose handling this sort of error? How can you guarantee that your program is left in a defined state? You cannot of course; you've already invoked undefined behavior. – Ed S. Jul 29 '13 at 00:53

1 Answers1

1

It's not possible in C++ but most platforms have some way for you to catch this error. Generally, about all you can do is shut down your application in a controlled way. At the point you catch the error, your process context is contaminated and unless you can fix the error, if you attempt to resume, it will just cause another exception.

I would suggest wrapping this DLL. In this case, using an executable just to service the DLL. Catch the exception (with Windows, use SetUnhandledExceptionFilter) and in the filter, just silently terminate. Have your main executable notice that the wrapper process disappeared and launch a new one. You can use one executable file if you have it take a parameter that causes it to start up as the wrapper.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278