Skip to contentSkip to conversation

scripts: fix memleak error in read_file

PATCH In review linfeilong 2 participants 3 messages Oct 22, 2019 – Oct 23, 2019

lore
Share & tools
lore

linfeilong

author
#0 lore raw

PATCH 1/1 scripts: fix memleak error in read_file

An error is found by the static code analysis tool: "memleak" Fix this by add free before return.

---
 scripts/insert-sys-cert.c | 1 +
 1 file changed, 1 insertion(+)
scripts/insert-sys-cert.c +1 -0
index 8902836..22d99a8 100644
@@ -250,6 +250,7 @@ static char *read_file(char *file_name, int *size)
 	}
 	if (read(fd, buf, *size) != *size) {
 		perror("File read failed");
+		free(buf);
 		close(fd);
 		return NULL;
 	}
Signature · 1 line
1.8.3.1
#1 lore raw
Quoted 13 lines · On Tue, 22 Oct 2019 11:47:59 +0000 linfeilong <[email protected]> wrote:

An error is found by the static code analysis tool: "memleak" Fix this by add free before return.

---
 scripts/insert-sys-cert.c | 1 +
 1 file changed, 1 insertion(+)
scripts/insert-sys-cert.c +0 -0
index 8902836..22d99a8 100644

scripts/insert-sys-cert.c static char *read_file(char *file_name, int *size) · line 256

Quoted 7 lines
scripts/insert-sys-cert.c +1 -0
@@ -250,6 +250,7 @@ static char *read_file(char *file_name, int *size)
 	}
 	if (read(fd, buf, *size) != *size) {
 		perror("File read failed");
+		free(buf);
 		close(fd);
 		return NULL;
 	}

A few lines later we do

	return buf;

so the patch adds a use-after-free error.

We could do a free(cert) down in main() or we could just do nothing - read_file() is only called a single time.

author
#2 lore raw
Quoted 24 lines · On Tue, 22 Oct 2019 11:47:59 +0000 linfeilong <[email protected]> wrote:
Quoted 14 lines

An error is found by the static code analysis tool: "memleak" Fix this by add free before return.

---
 scripts/insert-sys-cert.c | 1 +
 1 file changed, 1 insertion(+)
scripts/insert-sys-cert.c +0 -0
index 8902836..22d99a8 100644

scripts/insert-sys-cert.c static char *read_file(char *file_name, int *size) · line 256

Quoted 7 lines
scripts/insert-sys-cert.c +1 -0
@@ -250,6 +250,7 @@ static char *read_file(char *file_name, int *size)
 	}
 	if (read(fd, buf, *size) != *size) {
 		perror("File read failed");
+			free(buf);
 		close(fd);
 		return NULL;
 	}

A few lines later we do

Quoted 6 lines
	return buf;

so the patch adds a use-after-free error.

We could do a free(cert) down in main() or we could just do nothing - read_file() is only called a single time.

Thanks, but there is no use-after-free as we do free just before return NULL. And I think do free in error scenes makes the code look better.