From faff8bba5f7d253f71a0d1247247e6a097cce21a Mon Sep 17 00:00:00 2001 From: Dav999-v Date: Sat, 4 Mar 2023 01:29:19 +0100 Subject: [PATCH] Fix possible dangling pointers in FontContainer.map_name_idx The hashmap would get populated with the name of each font, as each font was being added. Unfortunately, adding a font would also realloc the storage for fonts, in which the names are also stored... Possibly invalidating the pointers to the names. This is now fixed by populating the hashmap after all the fonts are added. --- desktop_version/src/Font.cpp | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/desktop_version/src/Font.cpp b/desktop_version/src/Font.cpp index 5f3e4712..6859943a 100644 --- a/desktop_version/src/Font.cpp +++ b/desktop_version/src/Font.cpp @@ -286,12 +286,6 @@ static uint8_t load_font(FontContainer* container, const char* name) f->fallback_key[0] = '\0'; f->fallback_idx_valid = false; - if (container->map_name_idx == NULL) - { - container->map_name_idx = hashmap_create(); - } - hashmap_set(container->map_name_idx, f->name, SDL_strlen(f->name), f_idx); - bool white_teeth = false; tinyxml2::XMLDocument doc; @@ -555,6 +549,19 @@ void set_level_font_new(void) #endif } +static void fill_map_name_idx(FontContainer* container) +{ + /* Initialize the name->idx hashmap for the fonts in this container. + * This should only be done once, after all the fonts are added. */ + container->map_name_idx = hashmap_create(); + + for (uint8_t i = 0; i < container->count; i++) + { + Font* f = &container->fonts[i]; + hashmap_set(container->map_name_idx, f->name, SDL_strlen(f->name), i); + } +} + static void set_fallbacks(FontContainer* container) { /* Initialize the value of fallback_idx for all fonts in this container. @@ -609,6 +616,7 @@ void load_main(void) FILESYSTEM_freeEnumerate(&handle); font_idx_level = font_idx_8x8; + fill_map_name_idx(&fonts_main); set_fallbacks(&fonts_main); // Initialize the font menu options, 8x8 font first @@ -645,6 +653,7 @@ void load_custom(const char* name) } FILESYSTEM_freeEnumerate(&handle); + fill_map_name_idx(&fonts_custom); set_fallbacks(&fonts_custom); set_level_font(name);