]> diplodocus.org Git - nmh/commitdiff
Add mh_xstrdup() that exits on allocation failure.
authorRalph Corderoy <ralph@inputplus.co.uk>
Sun, 16 Oct 2016 21:53:23 +0000 (22:53 +0100)
committerRalph Corderoy <ralph@inputplus.co.uk>
Sun, 16 Oct 2016 21:53:23 +0000 (22:53 +0100)
Call it from a few simple places.

h/utils.h
sbr/ruserpass.c
sbr/utils.c

index c866a52..bd323d4 100644 (file)
--- 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);
 
index 7892cbf..bc24f52 100644 (file)
@@ -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);
     }
 
 }
index 5b7b19f..45ae9dd 100644 (file)
@@ -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)
 {