]> granicus.if.org Git - strace/commitdiff
xstrdup, xtrndup: allow NULL argument
authorEugene Syromiatnikov <evgsyr@gmail.com>
Thu, 24 Aug 2017 17:36:08 +0000 (17:36 +0000)
committerEugene Syromyatnikov <evgsyr@gmail.com>
Thu, 24 Aug 2017 18:06:54 +0000 (20:06 +0200)
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.

xmalloc.c
xmalloc.h

index 45ff57b1556159626b60ec81200105363ee77f6e..c2c50f8c618f69c026cc70233869cfea0b63032f 100644 (file)
--- a/xmalloc.c
+++ b/xmalloc.c
@@ -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
index ae0501dc83921cd48f04fadeceb4f7428fafa920..d1feeb91cda456fe743c47dd6a7203b7b2430333 100644 (file)
--- a/xmalloc.h
+++ b/xmalloc.h
@@ -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;