[flac-dev] [PATCH 3/2] Free memory on errors in all safe_realloc_*() functions

Miroslav Lichvar mlichvar at redhat.com
Fri Jul 20 11:04:50 UTC 2018


---
 include/share/alloc.h | 36 +++++++++++++++++++++++++-----------
 1 file changed, 25 insertions(+), 11 deletions(-)

diff --git a/include/share/alloc.h b/include/share/alloc.h
index 63878db0..97752f0c 100644
--- a/include/share/alloc.h
+++ b/include/share/alloc.h
@@ -174,34 +174,46 @@ static inline void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
 static inline void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
 {
 	size2 += size1;
-	if(size2 < size1)
+	if(size2 < size1) {
+		free(ptr);
 		return 0;
+	}
 	size3 += size2;
-	if(size3 < size2)
+	if(size3 < size2) {
+		free(ptr);
 		return 0;
-	return realloc(ptr, size3);
+	}
+	return safe_realloc_(ptr, size3);
 }
 
 static inline void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
 {
 	size2 += size1;
-	if(size2 < size1)
+	if(size2 < size1) {
+		free(ptr);
 		return 0;
+	}
 	size3 += size2;
-	if(size3 < size2)
+	if(size3 < size2) {
+		free(ptr);
 		return 0;
+	}
 	size4 += size3;
-	if(size4 < size3)
+	if(size4 < size3) {
+		free(ptr);
 		return 0;
-	return realloc(ptr, size4);
+	}
+	return safe_realloc_(ptr, size4);
 }
 
 static inline void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
 {
 	if(!size1 || !size2)
-		return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
-	if(size1 > SIZE_MAX / size2)
+		return safe_realloc_(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
+	if(size1 > SIZE_MAX / size2) {
+		free(ptr);
 		return 0;
+	}
 	return safe_realloc_(ptr, size1*size2);
 }
 
@@ -209,10 +221,12 @@ static inline void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
 static inline void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
 {
 	if(!size1 || (!size2 && !size3))
-		return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
+		return safe_realloc_(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
 	size2 += size3;
-	if(size2 < size3)
+	if(size2 < size3) {
+		free(ptr);
 		return 0;
+	}
 	return safe_realloc_mul_2op_(ptr, size1, size2);
 }
 
-- 
2.17.1



More information about the flac-dev mailing list