0

I have a function with a try catch block that looks like this:

bool apple()
{
    OutputDebugStringW(L"entered apple");
    try {
    SomeObj orange;
    int a = global_b->num; // global_b is NULL
    int b = global_b->someothernum; // global_b is NULL
    }
    catch(...) {
    OutputDebugStringW(L"leaving apple due to exception");
    return false;
    }
    OutputDebugStringW(L"leaving apple normally.");
    return true;
}

A single time in DbgView I saw this:

entered apple
leaving apple due to exception
leaving apple due to exception

The function is called on DllMain PROCESS_ATTACH. What's happening? Unfortunately I recompiled the code, and when I changed it back to the way it was in an attempt to reproduce the exception message appearing twice I couldn't.
This is in Visual Studio 2010 SP1 using DbgView 4.79. Has anyone ever seen something they output using OutputDebugString output twice?

Edit- Thanks to those who answered this. The answers point out that I cannot rely on a NULL pointer exception. In Visual Studio I use /EHa to catch everything as a C++ exception so that if there's any problem with any function I'm wrapping that I can just abort due to exception. Is it ok if I used /EHa to expect that access violations will be passed to catch(...)? I thought so.

loop
  • 3,460
  • 5
  • 34
  • 57

3 Answers3

0

Its undefined behavior (anything can happen (and seems too)):

int a = global_b->num; // global_b is NULL
int b = global_b->someothernum; // global_b is NULL

Access elements via a NULL pointer is undefined behavior. After this point your program is free to do anything so whatever you see is a valid output.

Martin York
  • 257,169
  • 86
  • 333
  • 562
  • I compile my DLL with `/EHa` to catch all exceptions as C++ exceptions. This is in Visual Studio. Isn't it defined behavior in Visual Studio? – loop Sep 30 '12 at 21:53
  • @test: Windows defines behavior for access violations, and Microsoft C++ links Windows exceptions (SEH) with C++ exceptions, but I don't think it guarantees that your code will produce an access violation, – Ben Voigt Sep 30 '12 at 23:23
0

You are relying on visual c++ specific behavior by catching an exception for access of a NULL pointer. So this is not a good way to code this behavior. Testing for NULL would be the right way to do this. See also ... How to catch the null pointer exception?

Community
  • 1
  • 1
combinatorial
  • 9,132
  • 4
  • 40
  • 58
0

Why not check for NULL then THROW the exception yourself, and see if that changes anything, might help to see if the undefined behavior is the cause of this or if indeed there is some other problem.

osirisgothra
  • 2,163
  • 24
  • 19