Poor man's exceptions in C

26 views
Skip to first unread message

Justin Meza

unread,
Dec 17, 2010, 1:50:48 PM12/17/10
to lci-devel
Finally found a way to avoid messy and error-prone deallocations after
exceptional conditions in C. Essentially, this technique (borrowed
from the Linux kernel) uses goto's to jump to some cleanup and return
code. For example, if a function allocates a, b, and c like so:

char *a = NULL;
char *b = NULL;
char *c = NULL;

a = malloc(sizeof(char));
b = malloc(sizeof(char));
c = malloc(sizeof(char));

normally, I would code the memory checks as follows:

char *a = NULL;
char *b = NULL;
char *c = NULL;

a = malloc(sizeof(char));
if (!a) return NULL;

b = malloc(sizeof(char));
if (!b) {
free(a);
return NULL;
}

c = malloc(sizeof(char));
if (!c) {
free(a);
free(b);
return NULL;
}

which means I've been needing to check which variables have been
allocated for a given control path; this can be annoying to keep track
of. The new exception technique goes something like this:

char *a = NULL;
char *b = NULL;
char *c = NULL;

a = malloc(sizeof(char));
if (!a) goto abort;
b = malloc(sizeof(char));
if (!b) goto abort;
c = malloc(sizeof(char));
if (!c) goto abort;

return something;
abort:
if (a) free(a);
if (b) free(b);
if (c) free(b);
return NULL;

Thanks to Chris Fallin for mentioning this technique to me.

glen lenker

unread,
Dec 17, 2010, 3:48:00 PM12/17/10
to lci-...@googlegroups.com
return something;
abort:
if (a) free(a);
if (b) free(b);
if (c) free(b); <-
return NULL;

Uh-oh! free'ing deallocated memory.

IIRC the first chapter of AUP suggested doing this inside of macros as
well. It always gives me bug riddled code soon afterwards, but its
nice in practice. I remember you as being fairly anti-macro :) come to
the dark side we have cookies.

Reply all
Reply to author
Forward
0 new messages