Catching Exception for deleting null pointers

I am studying exception handling in c++ and I run across this problem.

So I have a pointer that is uninitialized and tried deleting it.
When I ran the code the last message 'End' was not deleted.

What I did was read up on exception handling and use try catch blocks but I am not sure why I did not catch up on the error, even if I have a catch all.

I am using windows and mingw as compiler. It just exits without printing anything.

I maybe missing something I think.

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

int main()
{
    try
    {
        int *ptr;
        delete ptr;
    }
    catch (const std::runtime_error &e)
    {
        std::cerr << e.what() << '\n';
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << '\n';
    }
    catch (...)
    {
        std::cerr << "Unknown Exception!";
    }

    std::cout << "End!\n";

    return 0;
}
Deleting and uninitialized pointer generates undefined behavior which is unlikely be covered by exception handling.
Ohhh, need to take a mental note about this one. Is there somewhere a list of C++ things or transactions that may cause undefined behavior? This would be useful for C++ beginners.

Thank you!
Note that a null pointer is not the same as an uninitialized pointer. For a pointer to be null it has to be initialized to null. Using delete on a null pointer is safe and will do nothing.

Some of the most common causes of undefined behaviour from the top of my head:
* Using uninitialized objects.
* Accessing array elements with an index that is out of bounds.
* Dereferencing pointers that are invalid or null.
* Division by zero.
* Signed integer overflow.
* Reaching the end of a non-void function without return.
* Sometimes passing certain values to functions can be undefined, such as passing a null pointer to std::strlen, or passing INT_MIN to std::abs.

P1705 lists many more causes of undefined behaviour:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1705r1.html#trlook
Last edited on
Thank you very much! Kudos for sharing your expertise.
Topic archived. No new replies allowed.