2 ms·
The problem is NULL does not "fail fast". You could get a NULL pointer as an argument, and then not use that value until much later. Now when the bug shows up,
by johncolanduoni 11y ago
The problem is NULL does not "fail fast". You could get a NULL pointer as an argument, and then not use that value until much later. Now when the bug shows up, you'll have to work back through your code to even figure out where it came from.
> Use of a class type implementing an interface as a "null type" is a very good strategy.
Have you ever programmed Objective-C? It uses the null object pattern (called "nil") for all Objective-C objects. This makes it really easy to put big logic errors into your code, since calling upon a nil will just give you more nil. So now you have to wait even longer until a fatal error pops up, and then find where on earth the original nil came from.
> NULL and nullptr are convenient ways to do that without a ton of extra code.
How do you figure? If malloc can return NULL and you want a sane error message, you need to write a NULL check whenever you do a malloc. Otherwise, your user will just get a segfault, instead of a notification that it was memory they ran out of. So why not do that by default, and for the few places where you have prepared yourself to handle out of memory conditions use a different malloc which returns a value that must be explicitly checked?
- jschwartzi 11y agoBecause I don't have a system library that provides a different malloc. It's a property of my API that malloc returns NULL and I don't have any control over that. What I do have control over is what I do with data I get out of malloc. I have to check, somehow, for abnormal conditions. That is a requirement for using the malloc API. I get that this makes it hard to debug in some cases, so I might avoid that by religiously checking for NULL return from malloc and crashing immediately with a sensible error message. In the cases where getting a NULL return is not an error, like if I wrote a program to use as much heap as it can, I would ignore the NULL and proceed with the resources I can actually get.
- johncolanduoni 11y agoWhat stops you from writing an API on top of the system malloc that has two malloc functions like I described above, with return types that have unambiguous nullity? Then your religious NULL checks won't be duplicated (and you won't be able to stray from the righteous path and forget any).