by asveikau · 11y ago · 0 comments
One of my favorite tricks is to make your success case and your error cases look largely the same.
Say you have N allocations and N things that can fail. Lots of people get into trouble when they do:
void *p, *q, *r, *s;
p = a();
if (!p) { return ERROR; }
q = b();
if (!q) { free(p); return ERROR; }
r = c();
if (!r) { free(p); free(q); return ERROR; }
// etc..
And this madness just goes on and on. Add a new allocation? You potentially have to change n cleanup blocks.I breathe a lot easier when I can do [note we abuse the fact that free(NULL) is a no-op]:
void *p = NULL;
void *q = NULL;
void *r = NULL;
p = a();
if (!p) goto cleanup;
q = b();
if (!q) goto cleanup;
r = c();
if (!r) goto cleanup;
cleanup:
free(p);
free(q);
free(r);
What if the buffer at "r" needs to return something to the caller? It turns out it's really easy to transfer ownership in this pattern: // Success case. Give `r` to the caller.
*callerPointer = r;
r = NULL;
// Then we fall through to the failure block...
// r is null now so free(r) is harmless.
cleanup:
free(p);
free(q);
free(r);I think the C standard library would be easier to work with if they would've taken this further, and required, for example, fclose(NULL) to be a no-op.
There's always the counterargument that cleanup code that hides a missing allocation can mask bugs elsewhere, if for example a FILE * debug was never fopen()ed, only gets written to in exceptional cases, and fclose(NULL) ignores.
But I do make a point whenever I'm writing C, if I write a cleanup function for a new type of struct or whatever, cleaning up null is always a no-op. It just makes life slightly less tedious. Having to remember which functions do this and which don't, I'll admit, is annoying.
Depends on the detail of the use case of course, but assuming that NULL cleanup is more the exception than the rule this is definitely a case of profile it first for me.
if (p != NULL)
checks across your codebase will have a higher I$ footprint than sharing a single check inside free(), so the overall performance impact could easily be positive.http://www.openldap.org/devel/gitweb.cgi?p=openldap.git;a=co...
http://www.openldap.org/its/index.cgi/Software%20Bugs?id=778...
Although in your example, if the code really was doing only that much, I'd recognise the ||/&& "ladder" structure and write it like this instead:
if(!(p=a()) && (q=b()) && (r=c()))) {
free(p);
free(q);
free(r);
}I guess the other point I am trying to make is that success and failure can hit mostly the same code. Your snippet only checks for failure.
Hint: grep linux sources for "goto" and re-evaluate your life decisions. :P