diff mbox series

[V2,04/36] util: add safe version for realloc()

Message ID 20211114172733.71602-5-sbabic@denx.de
State Changes Requested
Headers show
Series DELTA Update | expand

Commit Message

Stefano Babic Nov. 14, 2021, 5:27 p.m. UTC
Realloc does not touch the passed pointer, creates a wrap-around
function to be sure that the memory on the heap is always freed.

Signed-off-by: Stefano Babic <sbabic@denx.de>
---
 core/util.c    | 12 ++++++++++++
 include/util.h |  1 +
 2 files changed, 13 insertions(+)
diff mbox series

Patch

diff --git a/core/util.c b/core/util.c
index da6bd10..f5d7c63 100644
--- a/core/util.c
+++ b/core/util.c
@@ -212,6 +212,18 @@  void freeargs (char **argv)
 	}
 }
 
+void *saferealloc(void *ptr, size_t size) {
+    void *ret = realloc(ptr, size);
+    /*
+     * Realloc does not touch the original block if fails.
+     * Policy is to free memory and returns with error (Null)
+     */
+    if (!ret && ptr)
+        free(ptr);
+    return ret;
+}
+
+
 /*
  * Concatente array of strings in a single string
  * The allocated string must be freed by the caller
diff --git a/include/util.h b/include/util.h
index 9c81e62..4f2995b 100644
--- a/include/util.h
+++ b/include/util.h
@@ -162,6 +162,7 @@  bool strtobool(const char *s);
  */
 typedef int (*writeimage) (void *out, const void *buf, unsigned int len);
 
+void *saferealloc(void *ptr, size_t size);
 int openfile(const char *filename);
 int copy_write(void *out, const void *buf, unsigned int len);
 #if defined(__FreeBSD__)