From 232237796ae40681c3a91bbdb3fd1d4c37279062 Mon Sep 17 00:00:00 2001 From: Koen Zandberg Date: Wed, 2 Sep 2020 19:16:30 +0200 Subject: [PATCH] memarray: Add memarray_calloc The memarray_alloc can be error prone to use as the block returned can contain data from previous uses. The memarray_calloc call added in this commit always zeroes the block before returning it to the user. --- sys/include/memarray.h | 14 ++++++++++++++ sys/memarray/memarray.c | 9 +++++++++ 2 files changed, 23 insertions(+) diff --git a/sys/include/memarray.h b/sys/include/memarray.h index 11ad4ed694..f1dec1439d 100644 --- a/sys/include/memarray.h +++ b/sys/include/memarray.h @@ -54,6 +54,8 @@ void memarray_init(memarray_t *mem, void *data, size_t size, size_t num); * * @pre `mem != NULL` * + * @note Allocated structure is not cleared before returned + * * @param[in,out] mem memarray pool to allocate block in * * @return pointer to allocated structure, if enough memory was available @@ -61,6 +63,18 @@ void memarray_init(memarray_t *mem, void *data, size_t size, size_t num); */ void *memarray_alloc(memarray_t *mem); +/** + * @brief Allocate and clear memory chunk in memarray pool + * + * @pre `mem != NULL` + * + * @param[in,out] mem memarray pool to allocate block in + * + * @return pointer to allocated structure, if enough memory was available + * @return NULL, on failure + */ +void *memarray_calloc(memarray_t *mem); + /** * @brief Free memory chunk in memarray pool * diff --git a/sys/memarray/memarray.c b/sys/memarray/memarray.c index 1ba007638c..c046697584 100644 --- a/sys/memarray/memarray.c +++ b/sys/memarray/memarray.c @@ -44,6 +44,15 @@ void *memarray_alloc(memarray_t *mem) return free; } +void *memarray_calloc(memarray_t *mem) +{ + void *new = memarray_alloc(mem); + if (new) { + memset(new, 0, mem->size); + } + return new; +} + void memarray_free(memarray_t *mem, void *ptr) { assert((mem != NULL) && (ptr != NULL));