util: fix mem leak of program path
authorEric Engestrom <eric.engestrom@intel.com>
Sun, 7 Jul 2019 10:40:04 +0000 (11:40 +0100)
committerEric Engestrom <eric.engestrom@intel.com>
Wed, 7 Aug 2019 07:42:42 +0000 (08:42 +0100)
Fixes: 759b94038987bb983398 ("util: Get program name based on path when possible")
Signed-off-by: Eric Engestrom <eric.engestrom@intel.com>
Reviewed-by: Tapani Pälli <tapani.palli@intel.com>
src/util/u_process.c

index cbccf48ed016ce6bed794240126d3fcb4142471a..371335303ec835b06dfa66337e6a3e5c2624adee 100644 (file)
 #undef GET_PROGRAM_NAME
 
 #if defined(__linux__) && defined(HAVE_PROGRAM_INVOCATION_NAME)
+
+static char *path = NULL;
+
+static void __freeProgramPath()
+{
+   free(path);
+   path = NULL;
+}
+
 static const char *
 __getProgramName()
 {
@@ -45,14 +54,10 @@ __getProgramName()
        * Strip these arguments out by using the realpath only if it was
        * a prefix of the invocation name.
        */
-      static char *path;
-
-      if (!path)
-         /* Note: realpath() allocates memory that we will keep around for
-          * the lifetime of the app, and then leak as the app closes.
-          * FIXME: we should find a way to clean this properly
-          */
+      if (!path) {
          path = realpath("/proc/self/exe", NULL);
+         atexit(__freeProgramPath);
+      }
 
       if (path && strncmp(path, program_invocation_name, strlen(path)) == 0) {
          /* This shouldn't be null because path is a a prefix,