From ce0d8a094c9d64e762b2b0ca451b043e85d202a5 Mon Sep 17 00:00:00 2001 From: Alexander Larsson Date: Wed, 24 Mar 2010 17:02:20 +0100 Subject: Add spice_strndup Also, make str(n)dup handle NULL correctly --- common/mem.c | 18 ++++++++++++++++++ common/mem.h | 1 + 2 files changed, 19 insertions(+) (limited to 'common') diff --git a/common/mem.c b/common/mem.c index ad0cccf6..56b37157 100644 --- a/common/mem.c +++ b/common/mem.c @@ -32,11 +32,29 @@ char *spice_strdup(const char *str) { char *copy; + if (str == NULL) { + return NULL; + } + copy = (char *)spice_malloc(strlen(str) + 1); strcpy(copy, str); return copy; } +char *spice_strndup(const char *str, size_t n_bytes) +{ + char *copy; + + if (str == NULL) { + return NULL; + } + + copy = (char *)spice_malloc(n_bytes + 1); + strncpy(copy, str, n_bytes); + copy[n_bytes] = 0; + return copy; +} + void *spice_memdup(const void *mem, size_t n_bytes) { void *copy; diff --git a/common/mem.h b/common/mem.h index f5fab20a..350e421e 100644 --- a/common/mem.h +++ b/common/mem.h @@ -23,6 +23,7 @@ #include char *spice_strdup(const char *str) SPICE_GNUC_MALLOC; +char *spice_strndup(const char *str, size_t n_bytes) SPICE_GNUC_MALLOC; void *spice_memdup(const void *mem, size_t n_bytes) SPICE_GNUC_MALLOC; void *spice_malloc(size_t n_bytes) SPICE_GNUC_MALLOC SPICE_GNUC_ALLOC_SIZE(1); void *spice_malloc0(size_t n_bytes) SPICE_GNUC_MALLOC SPICE_GNUC_ALLOC_SIZE(1); -- cgit