AUTHOR: Tobin Harding
Production C code should always check the return value of library
calls for errors. However, these checks often require writing the same
code repeatedly. There are a number of solutions to this problem, of
which this is just one.
For example
int foo (char *s) { char *buf; if ( (buf = malloc(strlen(s) + 1)) == NULL) /* error */ ... }
Often you would rather just ignore these error conditions but this is
production code right! By declaring a wrapper function
void *Malloc(size_t size);
and defining it
void *Malloc(size_t size) { void *ptr; if ( (ptr = malloc(size)) == NULL) { fprintf(stderr, "malloc error"); exit(EXIT_FAILURE); } return(ptr); }
we can then use this function in our code. The code snippet above can
now be written as
int foo (char *s) { char *buf; buf = Malloc(strlen(s) + 1); ... }
And we can continue on happy that we have checked the error
condition. If the requirements then change it is simply a matter of
updating the wrapper function to change behaviour across the whole
project.
Good Luck.
Attribution:
I was introduced to the ideas presented here by the text
UNIX Network Programming - Stevens, Fenner, and Rudoff