Discussion:
[PATCH] xmalloc: use native strndup if available
Johannes Weißl
2011-05-08 16:10:40 UTC
Permalink
- use native strndup if available
- provide fallback if strdup isn't available
---
configure | 5 +++++
xmalloc.c | 8 ++++----
xmalloc.h | 18 +++++++++++++++++-
3 files changed, 26 insertions(+), 5 deletions(-)

diff --git a/configure b/configure
index aa73669..29bb911 100755
--- a/configure
+++ b/configure
@@ -338,6 +338,8 @@ CONFIG_TREMOR=n
CONFIG_MIKMOD=n
USE_FALLBACK_IP=n
HAVE_BYTESWAP_H=n
+HAVE_STRDUP=n
+HAVE_STRNDUP=n
# unset CONFIG_* variables: if check succeeds 'y', otherwise 'n'

USAGE="
@@ -406,6 +408,8 @@ check check_rtsched
check check_ncurses
check check_iconv
check_header byteswap.h && HAVE_BYTESWAP_H=y
+check_function "strdup" && HAVE_STRDUP=y
+check_function "strndup" && HAVE_STRNDUP=y

check check_flac CONFIG_FLAC
check check_mad CONFIG_MAD
@@ -445,6 +449,7 @@ config_header config/curses.h HAVE_RESIZETERM HAVE_USE_DEFAULT_COLORS
config_header config/ffmpeg.h HAVE_FFMPEG_AVCODEC_H USE_FALLBACK_IP
config_header config/utils.h HAVE_BYTESWAP_H
config_header config/iconv.h HAVE_ICONV
+config_header config/xmalloc.h HAVE_STRDUP HAVE_STRNDUP

makefile_vars bindir datadir libdir mandir exampledir
makefile_vars CONFIG_FLAC CONFIG_MAD CONFIG_MIKMOD CONFIG_MODPLUG CONFIG_MPC CONFIG_VORBIS CONFIG_WAVPACK CONFIG_WAV CONFIG_MP4 CONFIG_AAC CONFIG_FFMPEG
diff --git a/xmalloc.c b/xmalloc.c
index 81d7d89..1605fd3 100644
--- a/xmalloc.c
+++ b/xmalloc.c
@@ -31,17 +31,17 @@ void malloc_fail(void)
exit(42);
}

+#ifndef HAVE_STRNDUP
char *xstrndup(const char *str, size_t n)
{
- int len;
+ size_t len;
char *s;

for (len = 0; len < n && str[len]; len++)
;
- s = malloc(len + 1);
- if (unlikely(s == NULL))
- malloc_fail();
+ s = xmalloc(len + 1);
memcpy(s, str, len);
s[len] = 0;
return s;
}
+#endif
diff --git a/xmalloc.h b/xmalloc.h
index b5c9ff7..1974e08 100644
--- a/xmalloc.h
+++ b/xmalloc.h
@@ -20,6 +20,7 @@
#define _XMALLOC_H

#include "compiler.h"
+#include "config/xmalloc.h"

#include <stdlib.h>
#include <string.h>
@@ -58,14 +59,29 @@ static inline void * __MALLOC xrealloc(void *ptr, size_t size)

static inline char * __MALLOC xstrdup(const char *str)
{
+#ifdef HAVE_STRDUP
char *s = strdup(str);
-
if (unlikely(s == NULL))
malloc_fail();
return s;
+#else
+ size_t size = strlen(str) + 1;
+ void *ptr = xmalloc(size);
+ return (char *) memcpy(ptr, str, size);
+#endif
}

+#ifdef HAVE_STRNDUP
+static inline char * __MALLOC xstrndup(const char *str, size_t n)
+{
+ char *s = strndup(str, n);
+ if (unlikely(s == NULL))
+ malloc_fail();
+ return s;
+}
+#else
char * __MALLOC xstrndup(const char *str, size_t n);
+#endif

static inline void free_str_array(char **array)
{
--
1.7.5.1
Gregory Petrosyan
2011-05-08 17:20:36 UTC
Permalink
Post by Johannes Weißl
- use native strndup if available
- provide fallback if strdup isn't available
Thanks, merged to master and maint!

Gregory

Loading...