Browse code

Introduce av_realloc_f.

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

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

Nicolas George authored on 2011/03/21 03:39:20
Showing 2 changed files
... ...
@@ -143,6 +143,21 @@ void *av_realloc(void *ptr, size_t size)
143 143
 #endif
144 144
 }
145 145
 
146
+void *av_realloc_f(void *ptr, size_t nelem, size_t elsize)
147
+{
148
+    size_t size;
149
+    void *r;
150
+
151
+    if (av_size_mult(elsize, nelem, &size)) {
152
+        av_free(ptr);
153
+        return NULL;
154
+    }
155
+    r = av_realloc(ptr, size);
156
+    if (!r && size)
157
+        av_free(ptr);
158
+    return r;
159
+}
160
+
146 161
 void av_free(void *ptr)
147 162
 {
148 163
 #if CONFIG_MEMALIGN_HACK
... ...
@@ -88,6 +88,16 @@ void *av_malloc(size_t size) av_malloc_attrib av_alloc_size(1);
88 88
 void *av_realloc(void *ptr, size_t size) av_alloc_size(2);
89 89
 
90 90
 /**
91
+ * Allocate or reallocate a block of memory.
92
+ * This function does the same thing as av_realloc, except:
93
+ * - It takes two arguments and checks the result of the multiplication for
94
+ *   integer overflow.
95
+ * - It frees the input block in case of failure, thus avoiding the memory
96
+ *   leak with the classic "buf = realloc(buf); if (!buf) return -1;".
97
+ */
98
+void *av_realloc_f(void *ptr, size_t nelem, size_t elsize);
99
+
100
+/**
91 101
  * Free a memory block which has been allocated with av_malloc(z)() or
92 102
  * av_realloc().
93 103
  * @param ptr Pointer to the memory block which should be freed.