[lxc-devel] strdup return value

Andrian Nord nightnord at gmail.com
Fri Nov 20 00:13:38 UTC 2009


On Wed, Nov 18, 2009 at 02:25:20AM +0300, Michael Tokarev wrote:
> Maybe it is better idea to define xmalloc()/xstrdup()
> that aborts if memory allocation failed, instead of
> scattering error checking all over?

For me, it seems to be generally better idea not to exit program itself,
but exit function with bad return value. In most of cases this is -1.

So, probably, maybe it could be done via macros?

--------------------------------------

/* eXtra Extended strdup (or eXtra Return strdup: xrstrdup): */
#define xestrdup(dst, src, onfail) do {			\
	dst = strdup(src);				\
							\
	if (!dst) {					\
		SYSERROR("failed to allocate memory");	\
		return onfail;				\
	}						\
} while(0)

/* eXtra strdup: */
#define xstrdup(dst, src) xestrdup(dst, src, -1)

---------------------------------------

Usage:

---------------------------------------

int ...() {
	...
	xstrdup(destination, source);
	...
	return 0;
}

char *...() {
	...
	xestrdup(destination, source, NULL);
	...
	return destination;
}

---------------------------------------

This is more ambigous, as requires explicit additional argument for
strtok, but for other string.h functions there will be no difference in
semantics.




More information about the lxc-devel mailing list