From: Ralph Corderoy Date: Sun, 16 Oct 2016 21:53:23 +0000 (+0100) Subject: Add mh_xstrdup() that exits on allocation failure. X-Git-Url: https://diplodocus.org/git/nmh/commitdiff_plain/1d4977af Add mh_xstrdup() that exits on allocation failure. Call it from a few simple places. --- diff --git a/h/utils.h b/h/utils.h index c866a52c..bd323d4e 100644 --- a/h/utils.h +++ b/h/utils.h @@ -12,6 +12,9 @@ void *mh_xrealloc(void *ptr, size_t size); /* Call calloc(3), exiting on NULL return. */ void *mh_xcalloc(size_t nelem, size_t elsize); +/* Duplicate a NUL-terminated string, exit on failure. */ +char *mh_xstrdup(char *src); + /* Call free(3), if ptr isn't NULL. */ void mh_xfree(void *ptr); diff --git a/sbr/ruserpass.c b/sbr/ruserpass.c index 7892cbfd..bc24f520 100644 --- a/sbr/ruserpass.c +++ b/sbr/ruserpass.c @@ -95,10 +95,8 @@ ruserpass(char *host, char **aname, char **apass) while ((t = token(tokval)) && t != MACH && t != DEFAULT) { switch(t) { case LOGIN: - if (token(tokval) && *aname == 0) { - *aname = mh_xmalloc((size_t) strlen(tokval) + 1); - strcpy(*aname, tokval); - } + if (token(tokval) && *aname == 0) + *aname = mh_xstrdup(tokval); break; case PASSWD: @@ -112,10 +110,8 @@ ruserpass(char *host, char **aname, char **apass) adios(NULL, "Remove password or correct file " "permissions."); } - if (token(tokval) && *apass == 0) { - *apass = mh_xmalloc((size_t) strlen(tokval) + 1); - strcpy(*apass, tokval); - } + if (token(tokval) && *apass == 0) + *apass = mh_xstrdup(tokval); break; case ACCOUNT: @@ -157,8 +153,7 @@ ruserpass(char *host, char **aname, char **apass) myname = tmp; } - *aname = mh_xmalloc((size_t) strlen(myname) + 1); - strcpy (*aname, myname); + *aname = mh_xstrdup(myname); } if (!*apass) { @@ -172,8 +167,7 @@ ruserpass(char *host, char **aname, char **apass) mypass = *aname; } - *apass = mh_xmalloc((size_t) strlen(mypass) + 1); - strcpy (*apass, mypass); + *aname = mh_xstrdup(mypass); } } diff --git a/sbr/utils.c b/sbr/utils.c index 5b7b19f1..45ae9ddf 100644 --- a/sbr/utils.c +++ b/sbr/utils.c @@ -76,6 +76,19 @@ void *mh_xcalloc(size_t nelem, size_t elsize) return p; } +/* Duplicate a NUL-terminated string, exit on failure. */ +char *mh_xstrdup(char *src) +{ + size_t n; + char *dest; + + n = strlen(src) + 1; /* Ignore possibility of overflow. */ + dest = mh_xmalloc(n); + memcpy(dest, src, n); + + return dest; +} + /* Call free(3), if ptr isn't NULL. */ void mh_xfree(void *ptr) {