[FFmpeg-cvslog] Introduce av_realloc_f.

Nicolas George git at videolan.org
Wed Sep 28 18:17:15 CEST 2011


ffmpeg | branch: master | Nicolas George <nicolas.george at normalesup.org> | Sun Mar 20 19:39:20 2011 +0100| [5cd754bca290775ec2dbbf88597ab58e0482efca] | committer: Michael Niedermayer

Introduce av_realloc_f.

av_realloc_f helps avoiding memory-leaks in typical uses of realloc.

Signed-off-by: Nicolas George <nicolas.george at normalesup.org>
Signed-off-by: Michael Niedermayer <michaelni at gmx.at>

> http://git.videolan.org/gitweb.cgi/ffmpeg.git/?a=commit;h=5cd754bca290775ec2dbbf88597ab58e0482efca
---

 libavutil/mem.c |   15 +++++++++++++++
 libavutil/mem.h |   10 ++++++++++
 2 files changed, 25 insertions(+), 0 deletions(-)

diff --git a/libavutil/mem.c b/libavutil/mem.c
index 44bfc8c..a58f432 100644
--- a/libavutil/mem.c
+++ b/libavutil/mem.c
@@ -143,6 +143,21 @@ void *av_realloc(void *ptr, size_t size)
 #endif
 }
 
+void *av_realloc_f(void *ptr, size_t nelem, size_t elsize)
+{
+    size_t size;
+    void *r;
+
+    if (av_size_mult(elsize, nelem, &size)) {
+        av_free(ptr);
+        return NULL;
+    }
+    r = av_realloc(ptr, size);
+    if (!r && size)
+        av_free(ptr);
+    return r;
+}
+
 void av_free(void *ptr)
 {
 #if CONFIG_MEMALIGN_HACK
diff --git a/libavutil/mem.h b/libavutil/mem.h
index ffdbb98..179e12f 100644
--- a/libavutil/mem.h
+++ b/libavutil/mem.h
@@ -88,6 +88,16 @@ void *av_malloc(size_t size) av_malloc_attrib av_alloc_size(1);
 void *av_realloc(void *ptr, size_t size) av_alloc_size(2);
 
 /**
+ * Allocate or reallocate a block of memory.
+ * This function does the same thing as av_realloc, except:
+ * - It takes two arguments and checks the result of the multiplication for
+ *   integer overflow.
+ * - It frees the input block in case of failure, thus avoiding the memory
+ *   leak with the classic "buf = realloc(buf); if (!buf) return -1;".
+ */
+void *av_realloc_f(void *ptr, size_t nelem, size_t elsize);
+
+/**
  * Free a memory block which has been allocated with av_malloc(z)() or
  * av_realloc().
  * @param ptr Pointer to the memory block which should be freed.



More information about the ffmpeg-cvslog mailing list