AmendHub

Download:

jcs

/

subtext

/

amendments

/

343

main_menu: Handle malloc failure, use grow_to_fit


jcs made amendment 343 about 1 year ago
--- main_menu.c Sun Feb 5 11:13:11 2023 +++ main_menu.c Thu Mar 2 09:38:45 2023 @@ -41,7 +41,9 @@ main_menu_init(void) if (default_menu == NULL) panic("Failed to find TEXT resource %d", MENU_DEFAULTS_ID); size = GetHandleSize(default_menu); - menu = xmalloc(size, "menu copy"); + menu = xmalloc(size); + if (menu == NULL) + panic("No memory for main menu"); HLock(default_menu); memcpy(menu, *default_menu, size); HUnlock(default_menu); @@ -79,16 +81,26 @@ main_menu_parse(char *opts, size_t len) short actionid, ret_count; struct main_menu_option *ret = NULL; -#define LINESIZE 1024 - line = xmalloc(LINESIZE, "parse_menu line"); - action = xmalloc(LINESIZE, "parse_menu action"); - menu_key = xmalloc(LINESIZE, "parse_menu menu_key"); - all_keys = xmalloc(LINESIZE, "parse_menu all_keys"); - label = xmalloc(LINESIZE, "parse_menu label"); - ret_count = 0; ret_size = 0; +#define LINESIZE 1024 + line = xmalloc(LINESIZE); + if (line == NULL) + goto parse_done; + action = xmalloc(LINESIZE); + if (action == NULL) + goto parse_done; + menu_key = xmalloc(LINESIZE); + if (menu_key == NULL) + goto parse_done; + all_keys = xmalloc(LINESIZE); + if (all_keys == NULL) + goto parse_done; + label = xmalloc(LINESIZE); + if (label == NULL) + goto parse_done; + for (n = 0, lastsep = 0, linenum = 0; n <= len; n++) { if (!(n == len || opts[n] == '\r')) continue; @@ -220,9 +232,12 @@ main_menu_parse(char *opts, size_t len) } strlcpy(label, line, LINESIZE); - EXPAND_TO_FIT(ret, ret_size, + if (!grow_to_fit(&ret, &ret_size, sizeof(struct main_menu_option) * ret_count, - sizeof(struct main_menu_option), 4); + sizeof(struct main_menu_option), 4)) { + ret_count = 0; + break; + } ret[ret_count].action = actionid; ret[ret_count].menu_key = menu_key[0]; @@ -232,21 +247,32 @@ main_menu_parse(char *opts, size_t len) ret_count++; } - xfree(&line); - xfree(&action); - xfree(&menu_key); - xfree(&all_keys); - xfree(&label); +parse_done: + if (line) + xfree(&line); + if (action) + xfree(&action); + if (menu_key) + xfree(&menu_key); + if (all_keys) + xfree(&all_keys); + if (label) + xfree(&label); if (ret_count == 0) { - xfree(&ret); + if (ret) + xfree(&ret); return NULL; } - EXPAND_TO_FIT(ret, ret_size, + if (!grow_to_fit(&ret, &ret_size, sizeof(struct main_menu_option) * ret_count, - sizeof(struct main_menu_option), 1); - + sizeof(struct main_menu_option), 1)) { + if (ret) + xfree(&ret); + return NULL; + } + ret[ret_count].action = ACTION_NONE; ret[ret_count].menu_key = 0; ret[ret_count].all_keys[0] = '\0';