From 6906c3431988978802ccfe2daef093a3ba31e9a8 Mon Sep 17 00:00:00 2001 From: Omar Chebib Date: Mon, 8 Aug 2022 15:39:25 +0800 Subject: [PATCH] heap: add a unit test for malloc(0) and slightly optimize heap_caps_malloc_prefer --- components/heap/heap_caps.c | 2 +- components/heap/test/test_malloc.c | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/components/heap/heap_caps.c b/components/heap/heap_caps.c index 19e45cfa6e..f3ac9460ee 100644 --- a/components/heap/heap_caps.c +++ b/components/heap/heap_caps.c @@ -267,7 +267,7 @@ IRAM_ATTR void *heap_caps_malloc_prefer( size_t size, size_t num, ... ) while (num--) { caps = va_arg( argp, uint32_t ); r = heap_caps_malloc_base( size, caps ); - if (r != NULL) { + if (r != NULL || size == 0) { break; } } diff --git a/components/heap/test/test_malloc.c b/components/heap/test/test_malloc.c index 6f4bbd8728..995a64da33 100644 --- a/components/heap/test/test_malloc.c +++ b/components/heap/test/test_malloc.c @@ -132,3 +132,25 @@ TEST_CASE("malloc(0) should return a NULL pointer", "[heap]") p = malloc(0); TEST_ASSERT(p == NULL); } + +static bool failure_occured = false; + +static void test_alloc_failure_callback(size_t size, uint32_t caps, const char * function_name) +{ + failure_occured = true; +} + +TEST_CASE("malloc/calloc(0) should not call failure callback", "[heap]") +{ + void* ptr = NULL; + esp_err_t ret = heap_caps_register_failed_alloc_callback(test_alloc_failure_callback); + TEST_ASSERT(ret == ESP_OK); + ptr = malloc(0); + TEST_ASSERT_NULL(ptr); + /* Check that our callback was NOT called */ + TEST_ASSERT_FALSE(failure_occured); + /* Do the same thing for calloc */ + ptr = calloc(0, 0); + TEST_ASSERT_NULL(ptr); + TEST_ASSERT_FALSE(failure_occured); +}