Skip to content

Commit

Permalink
lib: libc: minimal: add check on returned value
Browse files Browse the repository at this point in the history
Fix zephyrproject-rtos#32938 [Coverity CID :219508] "Unchecked return value in
lib/libc/minimal/source/stdlib/malloc.c"

The Coverity complains about sys_mutex_lock() which returns 0 if
locked. I added also the same check on returned value for
sys_mutex_unlock() which returns 0 if unlocked.

Signed-off-by: Guðni Már Gilbert <gudni.m.g@gmail.com>
  • Loading branch information
gudnimg authored and carlescufi committed Mar 23, 2021
1 parent 76f35f2 commit 952970d
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions lib/libc/minimal/source/stdlib/malloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,12 @@ void *malloc(size_t size)
errno = ENOMEM;
}

sys_mutex_unlock(&z_malloc_heap_mutex);
int unlock_ret = sys_mutex_unlock(&z_malloc_heap_mutex);

CHECKIF(unlock_ret != 0) {
return NULL;
}

return ret;
}

Expand All @@ -74,22 +79,31 @@ void *realloc(void *ptr, size_t requested_size)
}

void *ret = sys_heap_aligned_realloc(&z_malloc_heap, ptr,
__alignof__(z_max_align_t),
requested_size);
__alignof__(z_max_align_t),
requested_size);

if (ret == NULL && requested_size != 0) {
errno = ENOMEM;
}

sys_mutex_unlock(&z_malloc_heap_mutex);
int unlock_ret = sys_mutex_unlock(&z_malloc_heap_mutex);

CHECKIF(unlock_ret != 0) {
return NULL;
}
return ret;
}

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

CHECKIF(lock_ret != 0) {
return;
}

sys_heap_free(&z_malloc_heap, ptr);
sys_mutex_unlock(&z_malloc_heap_mutex);
(void) sys_mutex_unlock(&z_malloc_heap_mutex);
}

SYS_INIT(malloc_prepare, APPLICATION, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
Expand Down

0 comments on commit 952970d

Please sign in to comment.