3 ms·
True, some language features can indeed make defensive code bit less verbose, but I believe their value is overestimated. My approach in C code is usually to as
by ambrop7 13y ago
True, some language features can indeed make defensive code bit less verbose, but I believe their value is overestimated. My approach in C code is usually to assume no pointer argument is permitted to be null unless explicitly stated, and to not add null assertions (since if is null program will most likely crash which serves the purpose of the assertion). I don't remember seeing a null dereference bug in my code within the last year.
- oconnor0 13y agoAll extra overhead and possibility for error that could be avoided by a not allowing references to also contain not-a-reference.
- orclev 13y agoUnfortunately the problem with that approach is contained in the sentence "since if [a pointer] is null [the] program will most likely crash which serves the purpose of the assertion". It's that most likely part, you can't count on that, and in the case of a malicious actor if they can figure out a way to control the declaration of the null pointer (and yes, there are ways of doing this) you could be looking at an arbitrary code execution vulnerability. There's also the fact that a program crashing is quite often not considered an acceptable way to handle an error condition (it is true however that a crash from a null de-reference vs. a crash from a failed assertion is, aside from security implications, functionally identical). In a large code base, if values default to null or even intentionally return null, it can be very difficult to track down and handle every single case, particular if someone changes something way down in the guts of some function that changes a pointer in a data structure to a null, but that pointer never gets accessed until you're in some completely different area of code. Sure you can handle the null in the location it causes a failure at, but what if what you really want to do is figure out where the null came from and prevent it from being null in the first place? There's also the added advantage that adding extra effort to allow a value to be null is a nice subtle encouragement to not allow null values if possible in the first place.