From f227e90c248b37fe50c9e48a08a1bb976c782e9f Mon Sep 17 00:00:00 2001 From: michi_cc Date: Fri, 2 Sep 2011 20:54:51 +0000 Subject: (svn r22875) -Codechange: Add some asserts and checks to better prevent overflow of the argument to malloc. (monoid) --- src/core/alloc_func.hpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'src/core') diff --git a/src/core/alloc_func.hpp b/src/core/alloc_func.hpp index 6f70627ed..7bd09b004 100644 --- a/src/core/alloc_func.hpp +++ b/src/core/alloc_func.hpp @@ -42,6 +42,9 @@ static FORCEINLINE T *MallocT(size_t num_elements) */ if (num_elements == 0) return NULL; + /* Ensure the size does not overflow. */ + if (num_elements > SIZE_MAX / sizeof(T)) MallocError(SIZE_MAX); + T *t_ptr = (T*)malloc(num_elements * sizeof(T)); if (t_ptr == NULL) MallocError(num_elements * sizeof(T)); return t_ptr; @@ -96,12 +99,17 @@ static FORCEINLINE T *ReallocT(T *t_ptr, size_t num_elements) return NULL; } + /* Ensure the size does not overflow. */ + if (num_elements > SIZE_MAX / sizeof(T)) MallocError(SIZE_MAX); + t_ptr = (T*)realloc(t_ptr, num_elements * sizeof(T)); if (t_ptr == NULL) ReallocError(num_elements * sizeof(T)); return t_ptr; } /** alloca() has to be called in the parent function, so define AllocaM() as a macro */ -#define AllocaM(T, num_elements) ((T*)alloca((num_elements) * sizeof(T))) +#define AllocaM(T, num_elements) \ + ((num_elements) > SIZE_MAX / sizeof(T) && (MallocError(SIZE_MAX), NULL), \ + (T*)alloca((num_elements) * sizeof(T))) #endif /* ALLOC_FUNC_HPP */ -- cgit v1.2.3-70-g09d2