summaryrefslogtreecommitdiff
path: root/src/core/alloc_func.hpp
diff options
context:
space:
mode:
authormichi_cc <michi_cc@openttd.org>2011-09-02 20:54:51 +0000
committermichi_cc <michi_cc@openttd.org>2011-09-02 20:54:51 +0000
commitf227e90c248b37fe50c9e48a08a1bb976c782e9f (patch)
tree08d88d27ff581ebc89f0f16acb35d156ad6a84be /src/core/alloc_func.hpp
parent65637d89411e96dee5ee9fc2e8a7b3805c4162a2 (diff)
downloadopenttd-f227e90c248b37fe50c9e48a08a1bb976c782e9f.tar.xz
(svn r22875) -Codechange: Add some asserts and checks to better prevent overflow of the argument to malloc. (monoid)
Diffstat (limited to 'src/core/alloc_func.hpp')
-rw-r--r--src/core/alloc_func.hpp10
1 files changed, 9 insertions, 1 deletions
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 */