Skip to content

Commit

Permalink
Make xstrndup common
Browse files Browse the repository at this point in the history
This also improves the implementation to match how strndup is
specified (by GNU): if the length given is longer than the string,
only the string's length is allocated and copied, but the string need
not be null-terminated if it is at least as long as the given length.

Signed-off-by: Daniel Barkalow <barkalow@iabervon.org>
Signed-off-by: Junio C Hamano <junkio@cox.net>
  • Loading branch information
iabervon authored and Junio C Hamano committed May 4, 2007
1 parent cdda666 commit 5094102
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
8 changes: 0 additions & 8 deletions commit.c
Expand Up @@ -720,14 +720,6 @@ static char *logmsg_reencode(const struct commit *commit,
return out;
}

static char *xstrndup(const char *text, int len)
{
char *result = xmalloc(len + 1);
memcpy(result, text, len);
result[len] = '\0';
return result;
}

static void fill_person(struct interp *table, const char *msg, int len)
{
int start, end, tz = 0;
Expand Down
13 changes: 13 additions & 0 deletions git-compat-util.h
Expand Up @@ -189,6 +189,19 @@ static inline void *xmalloc(size_t size)
return ret;
}

static inline char *xstrndup(const char *str, size_t len)
{
char *p;

p = memchr(str, '\0', len);
if (p)
len = p - str;
p = xmalloc(len + 1);
memcpy(p, str, len);
p[len] = '\0';
return p;
}

static inline void *xrealloc(void *ptr, size_t size)
{
void *ret = realloc(ptr, size);
Expand Down

0 comments on commit 5094102

Please sign in to comment.