Mercurial > hg > toybox
changeset 1599:cd97856ca52c draft
Implement xstrncat() and fix xstrndup().
author | Rob Landley <rob@landley.net> |
---|---|
date | Thu, 04 Dec 2014 21:41:12 -0600 |
parents | 50daa0da1530 |
children | ce22ad7a26c1 |
files | lib/lib.h lib/xwrap.c |
diffstat | 2 files changed, 18 insertions(+), 4 deletions(-) [+] |
line wrap: on
line diff
--- a/lib/lib.h Thu Dec 04 16:42:01 2014 -0600 +++ b/lib/lib.h Thu Dec 04 21:41:12 2014 -0600 @@ -81,6 +81,7 @@ // xwrap.c void xstrncpy(char *dest, char *src, size_t size); +void xstrncat(char *dest, char *src, size_t size); void xexit(void) noreturn; void *xmalloc(size_t size); void *xzalloc(size_t size);
--- a/lib/xwrap.c Thu Dec 04 16:42:01 2014 -0600 +++ b/lib/xwrap.c Thu Dec 04 21:41:12 2014 -0600 @@ -9,13 +9,25 @@ #include "toys.h" -// Strcpy with size checking: exit if there's not enough space for the string. +// strcpy and strncat with size checking. Size is the total space in "dest", +// including null terminator. Exit if there's not enough space for the string +// (including space for the null terminator), because silently truncating is +// still broken behavior. (And leaving the string unterminated is INSANE.) void xstrncpy(char *dest, char *src, size_t size) { if (strlen(src)+1 > size) error_exit("'%s' > %ld bytes", src, (long)size); strcpy(dest, src); } +void xstrncat(char *dest, char *src, size_t size) +{ + long len = strlen(src); + + if (len+strlen(dest)+1 > size) + error_exit("'%s%s' > %ld bytes", src, (long)size); + strcpy(dest+len, src); +} + void xexit(void) { if (toys.rebound) longjmp(*toys.rebound, 1); @@ -52,9 +64,10 @@ // Die unless we can allocate a copy of this many bytes of string. char *xstrndup(char *s, size_t n) { - char *ret = xmalloc(++n); - strncpy(ret, s, n); - ret[--n]=0; + char *ret = strndup(s, ++n); + + if (!ret) error_exit("xstrndup"); + ret[--n] = 0; return ret; }