fix(checkbox): check for mem allocation failure in set_text (#4089)

This commit is contained in:
Carlos Diaz 2023-03-29 01:15:55 -06:00 committed by GitHub
parent 639e6b7b42
commit 609e2d34d7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 54 additions and 7 deletions

View File

@ -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);

View File

@ -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