Browse Source

util: introduce xstrndup helper

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>
main
Ahmad Fatoum 4 years ago committed by David Gibson
parent
commit
651410e54c
  1. 11
      util.c
  2. 1
      util.h

11
util.c

@ -33,6 +33,17 @@ char *xstrdup(const char *s)
return d; 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 xavsprintf_append(char **strp, const char *fmt, va_list ap)
{ {
int n, size = 0; /* start with 128 bytes */ int n, size = 0; /* start with 128 bytes */

1
util.h

@ -61,6 +61,7 @@ static inline void *xrealloc(void *p, size_t len)
} }


extern char *xstrdup(const char *s); 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(char **strp, const char *fmt, ...);
extern int PRINTF(2, 3) xasprintf_append(char **strp, const char *fmt, ...); extern int PRINTF(2, 3) xasprintf_append(char **strp, const char *fmt, ...);

Loading…
Cancel
Save