From: Baptiste Daroussin Date: Thu, 28 Apr 2022 08:37:33 +0000 (+0200) Subject: mydirname: rework and reduce the number of memory allocation X-Git-Tag: RELEASE_1_4_0a1~78 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=f904bb7269e8718664eeb7a2a9ca39de5b16f796;p=thirdparty%2Fmlmmj.git mydirname: rework and reduce the number of memory allocation --- diff --git a/src/strgen.c b/src/strgen.c index 5ce8cdf9..88ab24f2 100644 --- a/src/strgen.c +++ b/src/strgen.c @@ -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) diff --git a/tests/mlmmj.c b/tests/mlmmj.c index 0bf338d9..78a05530 100644 --- a/tests/mlmmj.c +++ b/tests/mlmmj.c @@ -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)