From 35ae300f2287f9d57e3ae38e5832150147fc82f0 Mon Sep 17 00:00:00 2001 From: Laurent Mazet Date: Thu, 13 Jun 2024 21:50:20 +0200 Subject: [PATCH] fix memory errors in caching --- function.c | 13 ++++++------- scrabble.c | 2 ++ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/function.c b/function.c index cec4f70..b0176c7 100644 --- a/function.c +++ b/function.c @@ -434,7 +434,7 @@ void findwords (word_t *words, play_t *play, play_t *turn) void checkspellingfromfile (word_t *words, char *dict) { - FILE *fd = fopen (dict, "r"); + FILE *fd = (dict) ? fopen (dict, "r") : NULL; if (fd) { int i; char str[128] = {0}; @@ -468,19 +468,18 @@ char **cachedictionary (char *dict) { char **listofwords = NULL; int nbwords = 0; - FILE *fd = fopen (dict, "r"); + FILE *fd = (dict) ? fopen (dict, "r") : NULL; if (fd) { char str[128] = {0}; - listofwords = (char **) calloc (NBWORDS + 1, sizeof (char *)); - CHECKALLOC (listofwords); while (fscanf (fd, "%s", str) > 0) { - listofwords[nbwords] = strdup (str); - CHECKALLOC (listofwords[nbwords]); - nbwords++; if (nbwords % NBWORDS == 0) { listofwords = (char **) realloc (listofwords, (nbwords + NBWORDS + 1) * sizeof (char *)); CHECKALLOC (listofwords); + memset (listofwords + nbwords, 0, (NBWORDS + 1) * sizeof (char *)); } + listofwords[nbwords] = strdup (str); + CHECKALLOC (listofwords[nbwords]); + nbwords++; } fclose (fd); } diff --git a/scrabble.c b/scrabble.c index d2d1b5a..8c1e1d0 100644 --- a/scrabble.c +++ b/scrabble.c @@ -388,5 +388,7 @@ int main (int argc, char *argv[]) /* test: echo q | scrabble.exe -l it */ /* test: echo q | scrabble.exe -l nl */ /* test: echo q | scrabble.exe -v 5 */ +/* test: echo vlvlvlvlvlvdkjjjjvlvlvlvlvlvdjjjjjvlvlvlvlvlvlvdq | scrabble.exe -l en -d dict/en.dict */ +/* test: echo vlvlvlvlvlvdkjjjjvlvlvlvlvlvdkvjvjvjvjvjvjvdklllvlvxccvq | scrabble.exe -d dict/fr.dict -c */ /* vim: set ts=4 sw=4 et: */ -- 2.30.2