[PATCH v2 1/4] libusbg: Fix potential memory leak in usbg_init()

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Memory allocated with asprintf() for variable path
could be not free() in some cases. Fix this issue by
doing some small refactoring.

Signed-off-by: Krzysztof Opasiak <k.opasiak@xxxxxxxxxxx>
---
 src/usbg.c |   35 ++++++++++++++++++++++++-----------
 1 file changed, 24 insertions(+), 11 deletions(-)

diff --git a/src/usbg.c b/src/usbg.c
index edb7fc3..d1fb0b2 100644
--- a/src/usbg.c
+++ b/src/usbg.c
@@ -1218,6 +1218,7 @@ int usbg_init(char *configfs_path, usbg_state **state)
 	int ret = USBG_SUCCESS;
 	DIR *dir;
 	char *path;
+	usbg_state *s;
 
 	ret = asprintf(&path, "%s/usb_gadget", configfs_path);
 	if (ret < 0)
@@ -1227,21 +1228,33 @@ int usbg_init(char *configfs_path, usbg_state **state)
 
 	/* Check if directory exist */
 	dir = opendir(path);
-	if (dir) {
-		closedir(dir);
-		*state = malloc(sizeof(usbg_state));
-		ret = *state ? usbg_init_state(path, *state)
-			 : USBG_ERROR_NO_MEM;
-		if (*state && ret != USBG_SUCCESS) {
-			ERRORNO("couldn't init gadget state\n");
-			usbg_free_state(*state);
-		}
-	} else {
+	if (!dir) {
 		ERRORNO("couldn't init gadget state\n");
 		ret = usbg_translate_error(errno);
-		free(path);
+		goto err;
+	}
+
+	closedir(dir);
+	s = malloc(sizeof(usbg_state));
+	if (!s) {
+		ret = USBG_ERROR_NO_MEM;
+		goto err;
 	}
 
+	ret = usbg_init_state(path, s);
+	if (ret != USBG_SUCCESS) {
+		ERRORNO("couldn't init gadget state\n");
+		usbg_free_state(s);
+		goto out;
+	}
+
+	*state = s;
+
+	return ret;
+
+err:
+	free(path);
+out:
 	return ret;
 }
 
-- 
1.7.9.5

--
To unsubscribe from this list: send the line "unsubscribe linux-usb" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html




[Index of Archives]     [Linux Media]     [Linux Input]     [Linux Audio Users]     [Yosemite News]     [Linux Kernel]     [Linux SCSI]     [Old Linux USB Devel Archive]

  Powered by Linux