Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my program catch an exception from dereferencing a null pointer?

Can some please explain why this exception isn't caught.

try {
    // This will cause an exception
    char *p = 0;
    char x = 0;
    *p = x;
}
catch (...) {
    int a = 0;
}

When I run the program it dies on the line *p = x. I would expect that the catch block would cause this exception to be ignored.

I'm using the Qt Creator (2.2) with Qt 4.7.2 compiling with Visual Studios 2008 on Windows 7 32 bit.

like image 226
Jon Avatar asked Nov 28 '22 17:11

Jon


1 Answers

There is no C++ exception being thrown here. You are causing undefined behavior because *p = x derefences a pointer with a null pointer value.

An exception is only propogated when you, or code you call, executes a throw expression. Undefined behaviour is not usually catchable.

like image 187
CB Bailey Avatar answered Dec 04 '22 23:12

CB Bailey