xstrdup, xtrndup: allow NULL argument

Accept NULL argument in xstrdup and xtrndup functions to allow use
of "xstrdup(str)" instead of "str ? xstrdup(str) : NULL".

* xmalloc.c (xstrdup, xstrndup): Handle NULL argument.
* xmalloc.h: Add comment regarding this deviation from the behaviour
of the POSIX counterparts of these functions.
This commit is contained in:
Eugene Syromiatnikov 2017-08-24 17:36:08 +00:00 committed by Eugene Syromyatnikov
parent 2b786e0113
commit 7ba0d89c9f
2 changed files with 13 additions and 0 deletions

View File

@ -91,6 +91,9 @@ xreallocarray(void *ptr, size_t nmemb, size_t size)
char *
xstrdup(const char *str)
{
if (!str)
return NULL;
char *p = strdup(str);
if (!p)
@ -104,6 +107,9 @@ xstrndup(const char *str, size_t n)
{
char *p;
if (!str)
return NULL;
#ifdef HAVE_STRNDUP
p = strndup(str, n);
#else

View File

@ -41,6 +41,13 @@ void *xcalloc(size_t nmemb, size_t size)
void *xmalloc(size_t size) ATTRIBUTE_MALLOC ATTRIBUTE_ALLOC_SIZE((1));
void *xreallocarray(void *ptr, size_t nmemb, size_t size)
ATTRIBUTE_ALLOC_SIZE((2, 3));
/*
* Note that the following two functions return NULL when NULL is specified
* and not when allocation is failed, since, as the "x" prefix implies,
* the allocation failure leads to program termination, so we may re-purpose
* this return value and simplify the idiom "str ? xstrdup(str) : NULL".
*/
char *xstrdup(const char *str) ATTRIBUTE_MALLOC;
char *xstrndup(const char *str, size_t n) ATTRIBUTE_MALLOC;