From f5c947e71ec6ca133f6672d1b45609430c4e9567 Mon Sep 17 00:00:00 2001 From: Tiago Cunha Date: Thu, 13 Dec 2012 15:02:15 +0000 Subject: [PATCH 1/3] Prevent crash when registering a toggle. It was counting one too many arguments, which would lead to a segfault when parsing the last command. --- commands.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/commands.c b/commands.c index e310fca..b04833d 100644 --- a/commands.c +++ b/commands.c @@ -125,7 +125,7 @@ toggle_list_create(int registr, int argc, char *argv[]) for (j = i; j < argc && strcmp("/", argv[j]); j++); /* now collapse them into a single string */ - cmd = argv2str(j - i + 1, argv + i); + cmd = argv2str(j - i, argv + i); toggle_list_add_command(t, cmd); free(cmd); From 852e81d2c8152e66174d974c876180076d2e11bb Mon Sep 17 00:00:00 2001 From: Tiago Cunha Date: Thu, 13 Dec 2012 15:33:11 +0000 Subject: [PATCH 2/3] Plug memory leak when removing a toggle. --- commands.c | 1 + 1 file changed, 1 insertion(+) diff --git a/commands.c b/commands.c index b04833d..9bdfa72 100644 --- a/commands.c +++ b/commands.c @@ -173,6 +173,7 @@ toggle_remove(int registr) if (!found) return; + toggle_list_free(toggleset[idx]); for (i = idx; i < toggleset_size - 1; i++) toggleset[i] = toggleset[i + 1]; From bcb9cc73bceca2a9b7bb8dbe6e2900101a6303e6 Mon Sep 17 00:00:00 2001 From: Tiago Cunha Date: Wed, 9 Jan 2013 11:35:24 +0000 Subject: [PATCH 3/3] It's valid to pass a NULL pointer to realloc. According to ANSI C it will behave like malloc. Take advantage of this and save a few lines. --- commands.c | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/commands.c b/commands.c index 9bdfa72..f219d63 100644 --- a/commands.c +++ b/commands.c @@ -78,28 +78,17 @@ void toggle_list_add_command(toggle_list *t, char *cmd) { char **new_cmds; - int idx; + int new_size; - /* resize array */ - if (t->size == 0) { - if ((t->commands = malloc(sizeof(char*))) == NULL) - err(1, "%s: malloc(3) failed", __FUNCTION__); + new_size = (t->size + 1) * sizeof *t->commands; + if ((new_cmds = realloc(t->commands, new_size)) == NULL) + err(1, "%s: realloc(3) failed", __FUNCTION__); + t->commands = new_cmds; - idx = 0; - t->size = 1; - } else { - int new_size = (t->size + 1) * sizeof(char*); - if ((new_cmds = realloc(t->commands, new_size)) == NULL) - err(1, "%s: realloc(3) failed", __FUNCTION__); - - idx = t->size; - t->commands = new_cmds; - t->size++; - } - - /* add command */ - if ((t->commands[idx] = strdup(cmd)) == NULL) + if ((t->commands[t->size] = strdup(cmd)) == NULL) err(1, "%s: strdup(3) failed", __FUNCTION__); + + t->size++; } toggle_list*