]> git.ipfire.org Git - thirdparty/mlmmj.git/commitdiff
mydirname: rework and reduce the number of memory allocation
authorBaptiste Daroussin <bapt@FreeBSD.org>
Thu, 28 Apr 2022 08:37:33 +0000 (10:37 +0200)
committerBaptiste Daroussin <bapt@FreeBSD.org>
Thu, 20 Oct 2022 13:51:06 +0000 (15:51 +0200)
src/strgen.c
tests/mlmmj.c

index 5ce8cdf9867abc3507cd9d94241bbc13e4be15d2..88ab24f2d8c6ddf65ee77563e4d57cdb9b370bb1 100644 (file)
@@ -169,17 +169,20 @@ char *hostnamestr()
 
 char *mydirname(const char *path)
 {
-       char *mypath, *dname, *ret;
-
-       mypath = xstrdup(path);
-       dname = dirname(mypath);
-       ret = xstrdup(dname);
-
-       /* We don't free mypath until we have strdup()'ed dname, because
-        * dirname() returns a pointer into mypath  -- mortenp 20040527 */
-       free(mypath);
-
-       return ret;
+       char *allocated;
+       char *walk;
+
+       if (path == NULL)
+               return (xstrdup("."));
+       allocated = xstrdup(path);
+       walk = strrchr(allocated, '/');
+       if (walk == NULL) {
+               allocated[0] = '.';
+               allocated[1] = '\0';
+       } else {
+               *walk = '\0';
+       }
+       return (allocated);
 }
 
 const char *mybasename(const char *path)
index 0bf338d9f9ecec75e8a35b0a93a598e88ecd1dd8..78a055306502cc273bd5ee925a4d7296aafc26ce 100644 (file)
@@ -152,7 +152,15 @@ ATF_TC_BODY(mydirname, tc)
 {
        char plop[] = "/path/to/a/file";
 
-       ATF_REQUIRE_STREQ(mydirname(plop), "/path/to/a");
+       char *t = mydirname(plop);
+       ATF_REQUIRE_STREQ(t, "/path/to/a");
+       free(t);
+       t = mydirname(NULL);
+       ATF_REQUIRE_STREQ(t, ".");
+       free(t);
+       t = mydirname("a");
+       ATF_REQUIRE_STREQ(t, ".");
+       free(t);
 }
 
 ATF_TC_BODY(mybasename, tc)