Skip to content

Commit

Permalink
libc/minimal: small fixes to malloc() and friends
Browse files Browse the repository at this point in the history
When malloc() is called with a size of 0 we should not set errno to
ENOMEM as there is no actual allocation failure in that case. This
duplicates the realloc() behavior.

Check the return value of sys_mutex_lock() in the free() case to make
Coverity happy.

Replace all CHECKIF() by explicit assertion statements to uniformize
those checks with the free() case which can't return errors.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
  • Loading branch information
Nicolas Pitre committed Mar 17, 2021
1 parent 101b96a commit 4d43926
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions lib/libc/minimal/source/stdlib/malloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
#include <sys/math_extras.h>
#include <string.h>
#include <app_memory/app_memdomain.h>
#include <sys/check.h>
#include <sys/mutex.h>
#include <sys/sys_heap.h>
#include <zephyr/types.h>
Expand All @@ -38,16 +37,15 @@ Z_GENERIC_SECTION(POOL_SECTION) static char z_malloc_heap_mem[HEAP_BYTES];

void *malloc(size_t size)
{
int lock_ret = sys_mutex_lock(&z_malloc_heap_mutex, K_FOREVER);
int lock_ret;

CHECKIF(lock_ret != 0) {
return NULL;
}
lock_ret = sys_mutex_lock(&z_malloc_heap_mutex, K_FOREVER);
__ASSERT_NO_MSG(lock_ret == 0);

void *ret = sys_heap_aligned_alloc(&z_malloc_heap,
__alignof__(z_max_align_t),
size);
if (ret == NULL) {
if (ret == NULL && size != 0) {
errno = ENOMEM;
}

Expand All @@ -67,11 +65,10 @@ static int malloc_prepare(const struct device *unused)

void *realloc(void *ptr, size_t requested_size)
{
int lock_ret = sys_mutex_lock(&z_malloc_heap_mutex, K_FOREVER);
int lock_ret;

CHECKIF(lock_ret != 0) {
return NULL;
}
lock_ret = sys_mutex_lock(&z_malloc_heap_mutex, K_FOREVER);
__ASSERT_NO_MSG(lock_ret == 0);

void *ret = sys_heap_aligned_realloc(&z_malloc_heap, ptr,
__alignof__(z_max_align_t),
Expand All @@ -87,7 +84,10 @@ void *realloc(void *ptr, size_t requested_size)

void free(void *ptr)
{
sys_mutex_lock(&z_malloc_heap_mutex, K_FOREVER);
int lock_ret;

lock_ret = sys_mutex_lock(&z_malloc_heap_mutex, K_FOREVER);
__ASSERT_NO_MSG(lock_ret == 0);
sys_heap_free(&z_malloc_heap, ptr);
sys_mutex_unlock(&z_malloc_heap_mutex);
}
Expand Down

0 comments on commit 4d43926

Please sign in to comment.