From 609e2d34d7c44ef371251acbc566b0d595c1b593 Mon Sep 17 00:00:00 2001 From: Carlos Diaz Date: Wed, 29 Mar 2023 01:15:55 -0600 Subject: [PATCH] fix(checkbox): check for mem allocation failure in set_text (#4089) --- src/widgets/checkbox/lv_checkbox.c | 23 ++++++++++++----- tests/src/test_cases/test_checkbox.c | 38 ++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 7 deletions(-) diff --git a/src/widgets/checkbox/lv_checkbox.c b/src/widgets/checkbox/lv_checkbox.c index 394908cb4..75bd6248f 100644 --- a/src/widgets/checkbox/lv_checkbox.c +++ b/src/widgets/checkbox/lv_checkbox.c @@ -68,21 +68,30 @@ lv_obj_t * lv_checkbox_create(lv_obj_t * parent) void lv_checkbox_set_text(lv_obj_t * obj, const char * txt) { lv_checkbox_t * cb = (lv_checkbox_t *)obj; + + if(NULL != txt) { + size_t len = 0; + #if LV_USE_ARABIC_PERSIAN_CHARS - size_t len = _lv_txt_ap_calc_bytes_cnt(txt); + len = _lv_txt_ap_calc_bytes_cnt(txt); #else - size_t len = strlen(txt); + len = strlen(txt); #endif - if(!cb->static_txt) cb->txt = lv_realloc(cb->txt, len + 1); - else cb->txt = lv_malloc(len + 1); + if(!cb->static_txt) cb->txt = lv_realloc(cb->txt, len + 1); + else cb->txt = lv_malloc(len + 1); + + LV_ASSERT_MALLOC(cb->txt); + if(NULL == cb->txt) return; + #if LV_USE_ARABIC_PERSIAN_CHARS - _lv_txt_ap_proc(txt, cb->txt); + _lv_txt_ap_proc(txt, cb->txt); #else - strcpy(cb->txt, txt); + strcpy(cb->txt, txt); #endif - cb->static_txt = 0; + cb->static_txt = 0; + } lv_obj_refresh_self_size(obj); lv_obj_invalidate(obj); diff --git a/tests/src/test_cases/test_checkbox.c b/tests/src/test_cases/test_checkbox.c index 4800e0b64..ae86d44b3 100644 --- a/tests/src/test_cases/test_checkbox.c +++ b/tests/src/test_cases/test_checkbox.c @@ -93,4 +93,42 @@ void test_checkbox_should_allocate_memory_for_static_text(void) LV_HEAP_CHECK(TEST_ASSERT_LESS_THAN(initial_available_memory, m1.free_size)); } +size_t malloc_calls = 0; + +void * malloc_stub(size_t size) +{ + (void) size; + malloc_calls++; + + return NULL; +} + +void test_checkbox_text_should_become_null_when_mem_allocation_fails(void) +{ + const char * message = "Hello World!"; + active_screen = lv_scr_act(); + checkbox = lv_checkbox_create(active_screen); + lv_test_malloc_set_cb(malloc_stub); + + lv_checkbox_set_text(checkbox, message); + + TEST_ASSERT_NULL(lv_checkbox_get_text(checkbox)); + + lv_test_malloc_set_cb(NULL); +} + +void test_checkbox_no_memory_allocation_when_refreshing_text(void) +{ + malloc_calls = 0; + active_screen = lv_scr_act(); + checkbox = lv_checkbox_create(active_screen); + lv_test_malloc_set_cb(malloc_stub); + + lv_checkbox_set_text(checkbox, NULL); + + TEST_ASSERT_EQUAL(0, malloc_calls); + + lv_test_malloc_set_cb(NULL); +} + #endif