From 70107c8f5c65bc9798d8f6b7f5b580997d0aca19 Mon Sep 17 00:00:00 2001 From: SzuWei Lin Date: Fri, 7 Apr 2017 18:56:13 +0800 Subject: Fix memory and file leak Bug: 35652061 Test: valgrind --leak-check=yes --show-reachable=yes ufdt_apply_overlay ... and result no leak Change-Id: Iec0fe77468d2fdf6c692209cd9571c02f96e2e44 --- tests/src/util.c | 34 +++++++++++++++++++++++----------- tests/src/util.h | 3 +-- 2 files changed, 24 insertions(+), 13 deletions(-) (limited to 'tests') diff --git a/tests/src/util.c b/tests/src/util.c index 0d8040d..1c76773 100644 --- a/tests/src/util.c +++ b/tests/src/util.c @@ -6,27 +6,39 @@ #include "libfdt.h" #include "libufdt_sysdeps.h" - -char *load_file(const char *filename, size_t *pLen) { - FILE *fp = fopen(filename, "r"); - if (!fp) { - return NULL; - } - +static char *load_file_contents(FILE *fp, size_t *len_ptr) { // Gets the file size. fseek(fp, 0, SEEK_END); size_t len = ftell(fp); fseek(fp, 0, SEEK_SET); - char *buf = dto_malloc(len); + char *buf = malloc(len); + if (buf == NULL) { + return NULL; + } + if (fread(buf, len, 1, fp) != 1) { - dto_free(buf); + free(buf); return NULL; } - if (pLen) { - *pLen = len; + if (len_ptr) { + *len_ptr = len; + } + + return buf; +} + +char *load_file(const char *filename, size_t *len_ptr) { + FILE *fp = fopen(filename, "r"); + if (!fp) { + return NULL; } + + char *buf = load_file_contents(fp, len_ptr); + + fclose(fp); + return buf; } diff --git a/tests/src/util.h b/tests/src/util.h index 9df0ae7..3b68e14 100644 --- a/tests/src/util.h +++ b/tests/src/util.h @@ -3,8 +3,7 @@ #include - -char *load_file(const char *filename, size_t *pLen); +char *load_file(const char *filename, size_t *len_ptr); int write_buf_to_file(const char *filename, const void *buf, size_t buf_size); int write_fdt_to_file(const char *filename, const void *fdt); -- cgit v1.2.3