From 457385d5f468f87c31b44ad8d0fec1cd743c627c Mon Sep 17 00:00:00 2001 From: Romain Vimont Date: Tue, 28 Feb 2023 21:48:18 +0100 Subject: [PATCH] Add sc_allocarray() util Add a function to allocate an array, which fails safely in the case where the multiplication would overflow. --- app/meson.build | 1 + app/src/util/memory.c | 14 ++++++++++++++ app/src/util/memory.h | 15 +++++++++++++++ 3 files changed, 30 insertions(+) create mode 100644 app/src/util/memory.c create mode 100644 app/src/util/memory.h diff --git a/app/meson.build b/app/meson.build index 7bdd288d..c24a17de 100644 --- a/app/meson.build +++ b/app/meson.build @@ -35,6 +35,7 @@ src = [ 'src/util/intmap.c', 'src/util/intr.c', 'src/util/log.c', + 'src/util/memory.c', 'src/util/net.c', 'src/util/net_intr.c', 'src/util/process.c', diff --git a/app/src/util/memory.c b/app/src/util/memory.c new file mode 100644 index 00000000..64ee616e --- /dev/null +++ b/app/src/util/memory.c @@ -0,0 +1,14 @@ +#include "memory.h" + +#include +#include + +void * +sc_allocarray(size_t nmemb, size_t size) { + size_t bytes; + if (__builtin_mul_overflow(nmemb, size, &bytes)) { + errno = ENOMEM; + return NULL; + } + return malloc(bytes); +} diff --git a/app/src/util/memory.h b/app/src/util/memory.h new file mode 100644 index 00000000..0fb6bc64 --- /dev/null +++ b/app/src/util/memory.h @@ -0,0 +1,15 @@ +#ifndef SC_MEMORY_H +#define SC_MEMORY_H + +#include + +/** + * Allocate an array of `nmemb` items of `size` bytes each + * + * Like calloc(), but without initialization. + * Like reallocarray(), but without reallocation. + */ +void * +sc_allocarray(size_t nmemb, size_t size); + +#endif