diff mbox series

[ndctl] daxctl/device: fix a memory leak in create-device

Message ID 20201219075220.4089532-1-vishal.l.verma@intel.com (mailing list archive)
State Accepted
Commit c33461b693158e30c29fe766a92fc8d22051f3ae
Headers show
Series [ndctl] daxctl/device: fix a memory leak in create-device | expand

Commit Message

Verma, Vishal L Dec. 19, 2020, 7:52 a.m. UTC
Static analysis reports that we neglected to free 'maps' which is used
to hold mappings parsed out of an input file. Free this at the end of
do_xaction_region so we don't leak any memory. Additionally, using local
variables for the calloc cause a scope warning. Fix this by just
allocating into the 'maps' variable directly. Give 'len' / 'nmaps' the
same treatment.

Fixes: 5bedb2a8197a ("daxctl: allow creating devices from input json")
Cc: Joao Martins <joao.m.martins@oracle.com>
Signed-off-by: Vishal Verma <vishal.l.verma@intel.com>
---
 daxctl/device.c | 26 ++++++++++++--------------
 1 file changed, 12 insertions(+), 14 deletions(-)
diff mbox series

Patch

diff --git a/daxctl/device.c b/daxctl/device.c
index 161025e..0721a57 100644
--- a/daxctl/device.c
+++ b/daxctl/device.c
@@ -157,10 +157,9 @@  static int sort_mappings(const void *a, const void *b)
 static int parse_device_file(const char *filename)
 {
 	struct json_object *jobj, *jval = NULL, *jmappings = NULL;
-	int i, len, rc = -EINVAL, region_id, id;
+	int i, rc = -EINVAL, region_id, id;
 	const char *chardev;
 	char  *region = NULL;
-	struct mapping *m;
 
 	jobj = json_object_from_file(filename);
 	if (!jobj)
@@ -187,12 +186,12 @@  static int parse_device_file(const char *filename)
 		return rc;
 	json_object_array_sort(jmappings, sort_mappings);
 
-	len = json_object_array_length(jmappings);
-	m = calloc(len, sizeof(*m));
-	if (!m)
+	nmaps = json_object_array_length(jmappings);
+	maps = calloc(nmaps, sizeof(*maps));
+	if (!maps)
 		return -ENOMEM;
 
-	for (i = 0; i < len; i++) {
+	for (i = 0; i < nmaps; i++) {
 		struct json_object *j, *val;
 
 		j = json_object_array_get_idx(jmappings, i);
@@ -201,23 +200,21 @@  static int parse_device_file(const char *filename)
 
 		if (!json_object_object_get_ex(j, "start", &val))
 			goto err;
-		m[i].start = json_object_get_int64(val);
+		maps[i].start = json_object_get_int64(val);
 
 		if (!json_object_object_get_ex(j, "end", &val))
 			goto err;
-		m[i].end = json_object_get_int64(val);
+		maps[i].end = json_object_get_int64(val);
 
 		if (!json_object_object_get_ex(j, "page_offset", &val))
 			goto err;
-		m[i].pgoff = json_object_get_int64(val);
+		maps[i].pgoff = json_object_get_int64(val);
 	}
-	maps = m;
-	nmaps = len;
-	rc = 0;
+
+	return 0;
 
 err:
-	if (!maps)
-		free(m);
+	free(maps);
 	return rc;
 }
 
@@ -817,6 +814,7 @@  static int do_xaction_region(enum device_action action,
 			break;
 		}
 	}
+	free(maps);
 
 	/*
 	 * jdevs is the containing json array for all devices we are reporting