开发者

How to understand the output?

int main(int argc, char** argv)
{
    try {
            char *p2 = NULL;
            cout << "p2:" << strlen(p2) <<endl; 
                    cout << "mark";
        }
        catch (...) {
      开发者_StackOverflow社区      cout << "caught exception" <<endl;
        }
    return 0;
}

The output is p2:,so neither cout << "mark"; nor cout << "caught exception" <<endl; got run,why?


In C++, dereferencing a NULL pointer causes undefined behavior, which means anything could happen: the computer could blow up, the function could return an arbitrary value, the program could be killed by an operating system exception (which, unlike a C++ expression, cannot be caught with try-catch).

In short, don't do it.

If you really need to do this for an extremely good reason (like working around a bug in a library you have absolutely no control over), look into your operating system support for such things (such as SEH on Windows).


On POSIX-compliant systems, your program receives the SIGSEGV signal and dies as soon as you call strlen(p2), since p2 is NULL.

To my knowledge, there's no way to portably catch segfaults using C++ exceptions.


Your code has undefined behavior. Therefore any output or no output are both valid results. My guess is that strlen is causing an access violation (at least on x86) and your program is being terminated.

C++ does not throw exceptions upon trying to dereference a null pointer.


strlen() doesn't throw exceptions, because it's a C function and C does not have exceptions. It just crashes your program when you give it bad input. (Although it is not required to.)


strlen(NULL) tries to dereference NULL pointer. This raises hardware exception which cannot be caught with try-catch mechanism. Program blows up. You would have the same scenario if you try to perform division by zero.

For this reason it is always a good practice to check whether pointers are (not) NULL. If pointer is NULL somewhere where it should not be (and you treat this as an exceptional situation), you can throw software exception from that place. Body of your catch block would have been executed If you had written something like this (before strlen call):

if(p2 == NULL)
    throw 1;

You forgot to add endl manipulator in line that prints "mark". It should be:

cout << "mark" << endl;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜