Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why null pointer dereference is not an exception

Tags:

c++

exception

The null pointer dereference usually results to runtime error and program crashes immediately. Why not to make these cases exceptional, throw exception and allow programmer to handle it runtime and keep program running?

like image 817
Igor Avatar asked Oct 27 '25 14:10

Igor


1 Answers

Because they would require an extraordinary level of runtime support, mandating checks on every single pointer access and vastly slowing down everybody's C++ programs whether they wanted this heavy-handed behaviour or not.

You are free to create a wrapper class that validates nullity on every access, and use that class when (and only when) you feel you need it. However, this would be considered a design smell, as you should never need such a device.

Instead, use proper memory management techniques that leave you without any null pointers whatsoever; the end of life of your pointees and your pointers should be the same.

like image 123
Lightness Races in Orbit Avatar answered Oct 29 '25 05:10

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!