From 03445e7bf9916a58a4b80d7062d577f38ed2b279 Mon Sep 17 00:00:00 2001
From: chenzhijia <chenzhijia@xiaomi.com>
Date: Tue, 14 May 2024 16:40:28 +0800
Subject: [PATCH] tlpi/users_groups:Fix memory leak in check_password

free memory before program exits

Change-Id: I28789b5ceaec4aaa45bb13f66cb3f61de1111841
Signed-off-by: chenzhijia <chenzhijia@xiaomi.com>
---

diff --git a/users_groups/check_password.c b/users_groups/check_password.c
index c142ac7..a70cbb6 100644
--- a/users_groups/check_password.c
+++ b/users_groups/check_password.c
@@ -30,6 +30,22 @@
 #include <shadow.h>
 #include "tlpi_hdr.h"
 
+#define fatal(msg)    \
+  do                  \
+    {                 \
+      free(username); \
+      fatal(msg);     \
+    }                 \
+  while (0)
+
+#define errExit(msg)  \
+  do                  \
+    {                 \
+      free(username); \
+      errExit(msg);   \
+    }                 \
+  while (0)
+
 int
 main(int argc, char *argv[])
 {
@@ -53,7 +69,7 @@
     printf("Username: ");
     fflush(stdout);
     if (fgets(username, lnmax, stdin) == NULL)
-        exit(EXIT_FAILURE);             /* Exit on EOF */
+        goto err;             /* Exit on EOF */
 
     len = strlen(username);
     if (username[len - 1] == '\n')
@@ -85,12 +101,17 @@
     authOk = strcmp(encrypted, pwd->pw_passwd) == 0;
     if (!authOk) {
         printf("Incorrect password\n");
-        exit(EXIT_FAILURE);
+        goto err;
     }
 
     printf("Successfully authenticated: UID=%ld\n", (long) pwd->pw_uid);
 
     /* Now do authenticated work... */
 
+    free(username);
     exit(EXIT_SUCCESS);
+
+err:
+    free(username);
+    exit(EXIT_FAILURE);
 }
