Skip to content

Commit

Permalink
util: introduce xstrndup helper
Browse files Browse the repository at this point in the history
We already have xstrdup, add xstrndup as well to make it
straight-forward to clone part of a string.

Signed-off-by: Ahmad Fatoum <a.fatoum@pengutronix.de>
  • Loading branch information
a3f authored and dgibson committed Jan 25, 2022
1 parent 4048aed commit 651410e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
11 changes: 11 additions & 0 deletions util.c
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,17 @@ char *xstrdup(const char *s)
return d;
}

char *xstrndup(const char *s, size_t n)
{
size_t len = strnlen(s, n) + 1;
char *d = xmalloc(len);

memcpy(d, s, len - 1);
d[len - 1] = '\0';

return d;
}

int xavsprintf_append(char **strp, const char *fmt, va_list ap)
{
int n, size = 0; /* start with 128 bytes */
Expand Down
1 change: 1 addition & 0 deletions util.h
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ static inline void *xrealloc(void *p, size_t len)
}

extern char *xstrdup(const char *s);
extern char *xstrndup(const char *s, size_t len);

extern int PRINTF(2, 3) xasprintf(char **strp, const char *fmt, ...);
extern int PRINTF(2, 3) xasprintf_append(char **strp, const char *fmt, ...);
Expand Down

0 comments on commit 651410e

Please sign in to comment.