Skip to content

Commit

Permalink
lib: *_new(): Use the new MALLOC_MULTIPLY() macro to avoid overflows
Browse files Browse the repository at this point in the history
Cast the sizeof() result to unsigned int, because it's definitely always
enough and in many cases this allows optimizing away the wrap-check.
  • Loading branch information
sirainen committed Dec 17, 2016
1 parent bbc11b4 commit 95ed21e
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/lib/data-stack.h
Expand Up @@ -87,7 +87,8 @@ bool t_try_realloc(void *mem, size_t size);
size_t t_get_bytes_available(void) ATTR_PURE;

#define t_new(type, count) \
((type *) t_malloc0(sizeof(type) * (count)))
((type *) t_malloc0(MALLOC_MULTIPLY((unsigned int)sizeof(type), (count))) + \
COMPILE_ERROR_IF_TRUE(sizeof(type) > UINT_MAX))

/* Returns pointer to a temporary buffer you can use. The buffer will be
invalid as soon as next t_malloc() is called!
Expand Down
3 changes: 2 additions & 1 deletion src/lib/mempool.h
Expand Up @@ -69,7 +69,8 @@ pool_t pool_datastack_create(void);
size_t pool_get_exp_grown_size(pool_t pool, size_t old_size, size_t min_size);

#define p_new(pool, type, count) \
((type *) p_malloc(pool, sizeof(type) * (count)))
((type *) p_malloc(pool, MALLOC_MULTIPLY((unsigned int)sizeof(type), (count))) + \
COMPILE_ERROR_IF_TRUE(sizeof(type) > UINT_MAX))
static inline void * ATTR_MALLOC ATTR_RETURNS_NONNULL
p_malloc(pool_t pool, size_t size)
{
Expand Down

0 comments on commit 95ed21e

Please sign in to comment.