CRoaring
CRoaring copied to clipboard
Should we implement standard `free` semantics for deallocation functions?
The standard library specifies free
to act as a nop
when its argument is a NULL
pointer. This gives us programmers a big convenience for error handling and similar situations where we don't need to add so many explicit branches, but rather count on free
doing the right thing for us. Point being, my proposal is not exactly something new.
Tackling #182 in particular would create (or, rather, acknowledge) many new error paths that will require these free
analogs to be called, and the current implementations also mean explicitly checking for NULL
each time on each call place. This can become tedious, error prone and a cognitive load rapidly.
It can also help brevity on existing code.
Counterarguments would probably go around the extra branching: sometimes we simply know for certain our pointer won't be NULL
. IMO this case shouldn't matter that much for performance for the following reasons:
- Where operation count matters the most is in tight loops, and it's folklore already that you shouldn't allocate too much if you'll be discarding the buffer there. If you allocate it should be because you do need to keep the value afterwards, so how fast the
free
function is is not the central concern. - Particularly error paths, and specifically those related to memory allocation, should be considered exceptional, and thus have low priority when it comes to performance. You'd rather optimize for the more common case, specially if your trade off is simply an extra branch.
Thoughts?
Yes. It is entirely fine to check for null when deallocating. Your rationale is excellent.