Home >Backend Development >C++ >Here are a few title options, keeping in mind the question format and addressing the core of the article: * Why Does Dereferencing a Null Pointer in C Not Throw an Exception? * How Do I Handle Unde
How to Handle Undefined Behavior in C
In C , dereferencing null pointers doesn't trigger an exception; it results in undefined behavior. This behavior often manifests as a segmentation fault or crash.
Consider the following code:
<code class="cpp">try { int* p = nullptr; *p = 1; } catch (...) { cout << "null pointer." << endl; }</code>
This attempt to catch the "null pointer exception" won't work because null pointer dereferencing isn't an exception in C . Instead, it evokes undefined behavior.
Solution: Manual Detection and Exception Throwing
In C , it's the programmer's responsibility to manually detect null pointers and throw an exception if encountered. This can be achieved with an explicit check before dereferencing:
<code class="cpp">if (p != nullptr) { *p = 1; } else { throw invalid_argument("null pointer"); }</code>
By explicitly throwing an exception, it can be caught in a try-catch block.
Note on C Implementations
Some C implementations, such as Visual C , may have features to "convert" system/hardware exceptions into C exceptions. However, this non-standard functionality comes with performance penalties and shouldn't be relied upon.
The above is the detailed content of Here are a few title options, keeping in mind the question format and addressing the core of the article: * Why Does Dereferencing a Null Pointer in C Not Throw an Exception? * How Do I Handle Unde. For more information, please follow other related articles on the PHP Chinese website!