[PATCH v2] fix segfault when trying to set options that have default values
Export this patch
this happens because, before setting an option, set_option() will try
to free the previous value (main.c around line 3127). however, the
options are not malloc()-allocated when they are the default values and
not read from the configuration file. this happens, for example, when
the configuration file doesn't exsist.
---
v2: use xstrdup() instead of strdup()
main.c | 24 +++++++++++++ -----------
1 file changed, 13 insertions(+), 11 deletions(-)
diff --git a/main.c b/main.c
index 17d0a2a..d51d77c 100644
--- a/main.c
+++ b/main.c
@@ -2532,6 +2532,7 @@ parse_config_string(const char *key, const char *val, enum option opt)
option_string_values(opt, &values, &nvalues);
for (size_t i = 0; i < nvalues; ++i) {
if (strcmp(val, values[i]) == 0) {
+ free(options[opt]);
options[opt] = xstrdup(values[i]);
return NULL;
}
@@ -2544,6 +2545,7 @@ parse_config_string(const char *key, const char *val, enum option opt)
while (lua_next(L, -2) != 0) {
const char *value = lua_tostring(L, -2);
if (value != NULL && strcmp(val, value) == 0) {
+ free(options[opt]);
options[opt] = xstrdup(value);
lua_pop(L, 3);
return NULL;
@@ -2745,17 +2747,17 @@ set_option_string(const char *key, const char *val, const char **restrict err)
static int
parse_config(void)
{
- options[OPT_COLORS] = "classic";
- options[OPT_GARBAGE_PILING] = "on";
- options[OPT_HARD_DROP] = "off";
- options[OPT_INPUT_HANDLER] = "vanilla";
- options[OPT_LINES_PER_LEVEL] = "vanilla";
- options[OPT_MUSIC] = "random";
- options[OPT_PAUSE] = "vanilla";
- options[OPT_RNG] = "classic";
- options[OPT_SAVE_HIGHSCORES] = "on";
- options[OPT_SFX] = "ntsc";
- options[OPT_SPEED] = "1/1";
+ options[OPT_COLORS] = xstrdup("classic");
+ options[OPT_GARBAGE_PILING] = xstrdup("on");
+ options[OPT_HARD_DROP] = xstrdup("off");
+ options[OPT_INPUT_HANDLER] = xstrdup("vanilla");
+ options[OPT_LINES_PER_LEVEL] = xstrdup("vanilla");
+ options[OPT_MUSIC] = xstrdup("random");
+ options[OPT_PAUSE] = xstrdup("vanilla");
+ options[OPT_RNG] = xstrdup("classic");
+ options[OPT_SAVE_HIGHSCORES] = xstrdup("on");
+ options[OPT_SFX] = xstrdup("ntsc");
+ options[OPT_SPEED] = xstrdup("1/1");
input[0].left[0].device = BIND_KEY;
input[0].left[0].key = SDLK_LEFT;
--
2.40.1
Still not a huge fan of this since the default values are almost always
immediately freed (if a config file is present), so the allocation is
unnecessary. But I'll take it for now, at least it fixes the segfault.
Thanks!
To gitsrht:~sebsite/generic-tetromino-game
8fc8509..cd852ea main -> main