The variable mapname is sometimes allocated and sometimes not.
To avoid double-free and still free allocated memory cleanly,
introduce a helper pointer for storing possibly allocated memory.

Signed-off-by: Martin Wilck <[email protected]>
---
 kpartx/kpartx.c | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)

diff --git a/kpartx/kpartx.c b/kpartx/kpartx.c
index 7ec89b4..6f2ec4e 100644
--- a/kpartx/kpartx.c
+++ b/kpartx/kpartx.c
@@ -245,7 +245,8 @@ main(int argc, char **argv){
        char *loopdev __attribute__((cleanup(cleanup_charp))) = NULL;
        char *delim __attribute__((cleanup(cleanup_charp))) = NULL;
        char *uuid __attribute__((cleanup(cleanup_charp))) = NULL;
-       char *mapname __attribute__((cleanup(cleanup_charp))) = NULL;
+       char *_mapname __attribute__((cleanup(cleanup_charp))) = NULL;
+       char *mapname;
        int hotplug = 0;
        int loopcreated = 0;
        struct stat buf;
@@ -388,11 +389,15 @@ main(int argc, char **argv){
        off = find_devname_offset(device);
 
        if (!loopdev) {
-               mapname = dm_mapname(major(buf.st_rdev), minor(buf.st_rdev));
-               if (mapname)
-                       uuid = dm_mapuuid(mapname);
+               _mapname = dm_mapname(major(buf.st_rdev), minor(buf.st_rdev));
+               if (_mapname)
+                       uuid = dm_mapuuid(_mapname);
        }
 
+       mapname = _mapname;
+       if (!mapname)
+               mapname = device + off;
+
        /*
         * We are called for a non-DM device.
         * Make up a fake UUID for the device, unless "-d -f" is given.
@@ -402,9 +407,6 @@ main(int argc, char **argv){
        if (!uuid && !(what == DELETE && force_devmap))
                uuid = nondm_create_uuid(buf.st_rdev);
 
-       if (!mapname)
-               mapname = device + off;
-
        if (delim == NULL) {
                delim = xmalloc(DELIM_SIZE);
                memset(delim, 0, DELIM_SIZE);
-- 
2.52.0


Reply via email to