From f1ca2213fa649a9e3635ec7638b6c5bced594787 Mon Sep 17 00:00:00 2001 From: Joe Marcus Clarke Date: Wed, 20 Aug 2008 20:51:29 +0200 Subject: Implement ca_strdup for platforms that lack it natively Signed-off-by: Lennart Poettering --- src/malloc.c | 25 +++++++++++++++++++++++++ src/malloc.h | 8 ++++++++ 2 files changed, 33 insertions(+) (limited to 'src') diff --git a/src/malloc.c b/src/malloc.c index e32cc1b..9592af4 100644 --- a/src/malloc.c +++ b/src/malloc.c @@ -58,3 +58,28 @@ char *ca_sprintf_malloc(const char *format, ...) { size *= 2; } } + +#ifndef HAVE_STRNDUP +char *ca_strndup(const char *s, size_t n) { + size_t n_avail; + char *p; + + if (!s) + return NULL; + + if (memchr(s, '\0', n)) { + n_avail = strlen(s); + if (n_avail > n) + n_avail = n; + } else + n_avail = n; + + if (!(p = ca_new(char, n_avail + 1))) + return NULL; + + memcpy(p, s, n_avail); + p[n_avail] = '\0'; + + return p; +} +#endif diff --git a/src/malloc.h b/src/malloc.h index 30f0216..6073e03 100644 --- a/src/malloc.h +++ b/src/malloc.h @@ -27,11 +27,19 @@ #include "canberra.h" #include "macro.h" +#ifndef PACKAGE +#error "Please include config.h before including this file!" +#endif + #define ca_malloc malloc #define ca_free free #define ca_malloc0(size) calloc(1, (size)) #define ca_strdup strdup +#ifdef HAVE_STRNDUP #define ca_strndup strndup +#else +char *ca_strndup(const char *s, size_t n); +#endif void* ca_memdup(const void* p, size_t size); -- cgit