Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null pointers and application crashing

Tags:

c++

pointers

This is more of a theoretical question. Why do c++ applications crash when following null pointers?

Is the crashing mechanic there on purpose to protect the system the app is running on or an unavoided fact the comes from the very core of the language? If it is the latter, is automatic handling of null pointers something that could be expected in the future?

like image 905
Balgy Avatar asked Jun 14 '26 17:06

Balgy


1 Answers

C++ applications can crash when following null pointers. Nothing in the C++ standard says they will. The attempt to dereference a null pointer invokes what is called "undefined behavior", meaning the standard refuses to say what can happen.

As for why most cases result in a crash, most compilers cheat and make a null pointer point at byte 0, and many OSes make address 0 unwritable (and sometimes unreadable as well) so attempts to access the address trigger a processor fault.

As for automatically handling the problem, that's exactly the point of triggering a fault. (The alternative would be to let the program run amok.) There's no further automation that can be done past that point -- the program has gone off the rails and can't be trusted, and the OS has no way to know what you were trying to point at.

like image 86
cHao Avatar answered Jun 17 '26 08:06

cHao



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!