diff options
author | michi_cc <michi_cc@openttd.org> | 2011-09-02 20:54:51 +0000 |
---|---|---|
committer | michi_cc <michi_cc@openttd.org> | 2011-09-02 20:54:51 +0000 |
commit | f227e90c248b37fe50c9e48a08a1bb976c782e9f (patch) | |
tree | 08d88d27ff581ebc89f0f16acb35d156ad6a84be /src/core | |
parent | 65637d89411e96dee5ee9fc2e8a7b3805c4162a2 (diff) | |
download | openttd-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')
-rw-r--r-- | src/core/alloc_func.hpp | 10 |
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 */ |