From a1df9fca4f723915e0aef01ab2d0d02933131adf Mon Sep 17 00:00:00 2001 From: Michael Date: Sat, 10 Oct 2026 01:04:11 +0200 Subject: [PATCH] fix: resize arrays as much as needed --- src/msh.c | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/msh.c b/src/msh.c index 3a080e9..e9a4bb1 100644 --- a/src/msh.c +++ b/src/msh.c @@ -17,8 +17,9 @@ #define HISTORY_FILE_NAME "/history.log" #define LOCAL_SHARE_DIRNAME "/.local/share/msh" -#define DEFAULTLINECAPACITY 128 -#define DEFAULTTOKENSCAPACITY 32 +#define DEFAULTLINECAPACITY 256 +#define DEFAULTTOKENSCAPACITY 64 +#define DEFAULTHISTORYCAPACITY 128 const int LINESIZE = 512; @@ -267,8 +268,13 @@ int main(int argc, char** argv) { } tokenworkcapacity = DEFAULTLINECAPACITY; - historycapacity = 16; + historycapacity = DEFAULTHISTORYCAPACITY; history = calloc(historycapacity, sizeof(char*)); + if (history == NULL) { + retval = 1; + goto cleanup; + } + memset(history, 0, historycapacity); // Main loop while(1) { @@ -379,7 +385,7 @@ int main(int argc, char** argv) { linelen++; // Are we out of capacity? Double line length - if (linelen >= linecapacity - 1) { + while (linelen >= linecapacity - 1) { linecapacity *= 2; line = realloc(line, linecapacity); if (line == NULL) { @@ -409,7 +415,7 @@ print_prompt: fprintf(historyfile, "%s\n", line); fflush(historyfile); - if (tokenworkcapacity < linelen - 1) { + while (tokenworkcapacity < linelen - 1) { tokenworkcapacity *= 2; tokenwork = realloc(tokenwork, tokenworkcapacity); } @@ -422,8 +428,7 @@ print_prompt: } - // TEMPORARY - if (historyi >= historycapacity) { + while (historyi >= historycapacity) { historycapacity *= 2; history = reallocarray(history, historycapacity, sizeof(char*)); @@ -431,6 +436,7 @@ print_prompt: retval = 1; goto cleanup; } + memset(history + historyi, 0, (historycapacity - historyi) * sizeof(char*)); } // change ownership of line to history history[historyi++] = line; @@ -448,7 +454,7 @@ print_prompt: tokens[ntokens] = token; - if (ntokens >= tokenscapacity - 1) { + while (ntokens >= tokenscapacity - 1) { tokenscapacity *= 2; tokens = reallocarray(tokens, tokenscapacity, sizeof(char*)); }