From: Carl Worth Date: Tue, 1 Dec 2009 20:51:39 +0000 (-0800) Subject: xutil: Implement xstrndup without relying on strndup. X-Git-Tag: 0.1~267 X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=8b445212e46a194b59edbd6857449430fe460165;p=notmuch.git xutil: Implement xstrndup without relying on strndup. Since we need to do this for portability, (some systems don't have a strndup function), we might as well do it unconditionally. There's almost no disadvantage to doing so, and this has the advantages of not requiring a configure-time check nor having two different implementations, one of which would often be less tested. --- diff --git a/TODO b/TODO index 1b8fb42a..87f84a42 100644 --- a/TODO +++ b/TODO @@ -41,8 +41,6 @@ Portability ----------- Fix configure script to test each compiler warning we want to use. -Implement strndup locally (or call talloc_strndup instead). - Implement getline locally, (look at gnulib). Completion diff --git a/lib/xutil.c b/lib/xutil.c index 6fa5eb0d..268225b8 100644 --- a/lib/xutil.c +++ b/lib/xutil.c @@ -18,7 +18,6 @@ * Author: Carl Worth */ -#define _GNU_SOURCE /* For strndup */ #include "notmuch-private.h" #include @@ -84,11 +83,16 @@ xstrndup (const char *s, size_t n) { char *ret; - ret = strndup (s, n); + if (strlen (s) <= n) + n = strlen (s); + + ret = malloc (n + 1); if (ret == NULL) { fprintf (stderr, "Out of memory.\n"); exit (1); } + memcpy (ret, s, n); + ret[n] = '\0'; return ret; }