Subject: error checking wrapper function proposal
To: None <tech-userlevel@netbsd.org>
From: Christos Zoulas <christos@zoulas.com>
List: tech-userlevel
Date: 06/16/2006 10:50:27
I've been thinking of adding a small layer of error/detect exit routines
for commonly used routines. My reasoning for this is:

1. many programs do this on their own, and this would centralize it
2. some programs do not bother checking at all
3. some programs open code this and it quickly gets tedious, and makes
   reading the code more difficult
4. a handful of programs do the checks incorrectly

void
estrlcpy(char *dst, const char *src, size_t len)
{
       if (strlcpy(dst, src, len) >= len) {
	       errno = ENAMETOOLONG;
	       err(1, "Cannot copy `%s'", src);
       }
}

void
estrlcat(char *dst, const char *src, size_t len)
{
       if (strlcat(dst, src, len) >= len) {
	       errno = ENAMETOOLONG;
	       err(1, "Cannot append `%s'", src);
       }
}

void *
emalloc(size_t n)
{
	void *p = malloc(n);
	if (p == NULL)
		err(1, "Cannot allocate %zu bytes", n);
	return p;
}

void *
erealloc(void *p, size_t n)
{
	void *q = realloc(p, n);
	if (q == NULL)
		err(1, "Cannot re-allocate %zu bytes", n);
	return q;
}

char *
estrdup(const char *s)
{
	char *d = strdup(s);
	if (d == NULL)
		err(1, "Cannot copy `%s'", s);
	return d;
}

FILE *
efopen(const char *p, const char *m)
{
	FILE *fp = fopen(p, m);
	if (fp == NULL)
		err(1, "Cannot open `%s'", p);
	return fp;
}

These could go in libutil, and declared in <err.h>. Some programs already
define some of them already so that would save code/maintenance etc.

Opinions?

christos