diff options
author | Eugene Syromyatnikov <evgsyr@gmail.com> | 2021-08-22 17:52:57 +0200 |
---|---|---|
committer | Eugene Syromyatnikov <evgsyr@gmail.com> | 2021-08-24 17:17:53 +0200 |
commit | 17c10740cb7f4e5a738c6f4bfb88e13f4e1f01a7 (patch) | |
tree | 5009628a56cce92638366887dea6728cdae5942f | |
parent | 6a9b30b2066d71a9954f73c317530ab25afc4b53 (diff) | |
download | strace-17c10740cb7f4e5a738c6f4bfb88e13f4e1f01a7.tar.gz |
xmalloc: add xmemdup and xarraydup utility functions
There are multiple instances of using pair of x*alloc and memcpy calls
to duplicate an entity; sometimes they even utilise xcalloc and perform
unnecessary zeroing of the memory. Implement a separate routine
that allows more compact code.
* src/xmalloc.h (xmemdup, xarraydup): New declarations.
(xobjdup): New macro, a wrapper for xmemdup.
* src/xmalloc.c (xmemdup, xarraydup): New functions.
-rw-r--r-- | src/xmalloc.c | 19 | ||||
-rw-r--r-- | src/xmalloc.h | 11 |
2 files changed, 29 insertions, 1 deletions
diff --git a/src/xmalloc.c b/src/xmalloc.c index be5e601e1..527e7c56e 100644 --- a/src/xmalloc.c +++ b/src/xmalloc.c @@ -150,6 +150,25 @@ xstrndup(const char *str, size_t n) return p; } +void * +xmemdup(const void *src, size_t size) +{ + if (!src) + return NULL; + + return memcpy(xmalloc(size), src, size); +} + +void * +xarraydup(const void *src, size_t nmemb, size_t memb_size) +{ + if (!src) + return NULL; + + /* (nmemb * memb_size) checks are already done inside xallocarray */ + return memcpy(xallocarray(nmemb, memb_size), src, nmemb * memb_size); +} + char * xasprintf(const char *fmt, ...) { diff --git a/src/xmalloc.h b/src/xmalloc.h index 505c64739..94d2689b0 100644 --- a/src/xmalloc.h +++ b/src/xmalloc.h @@ -69,7 +69,7 @@ void *xreallocarray(void *ptr, size_t nmemb, size_t size) void *xgrowarray(void *ptr, size_t *nmemb, size_t memb_size); /* - * Note that the following two functions return NULL when NULL is specified + * Note that the following four 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". @@ -77,6 +77,15 @@ void *xgrowarray(void *ptr, size_t *nmemb, size_t memb_size); char *xstrdup(const char *str) ATTRIBUTE_MALLOC; char *xstrndup(const char *str, size_t n) ATTRIBUTE_MALLOC; +/** Implements xmalloc + memcpy idiom. */ +void *xmemdup(const void *src, size_t size) + ATTRIBUTE_MALLOC ATTRIBUTE_ALLOC_SIZE((2)); +/** Implements xallocarray + memcpy idiom. */ +void *xarraydup(const void *src, size_t nmemb, size_t memb_size) + ATTRIBUTE_MALLOC ATTRIBUTE_ALLOC_SIZE((2, 3)); + +#define xobjdup(src_) xmemdup(src_, sizeof(*(src_))) + /** * Analogous to asprintf, die in case of an error. */ |