fix memory errors in caching
authorLaurent Mazet <mazet@softndesign.org>
Thu, 13 Jun 2024 19:50:20 +0000 (21:50 +0200)
committerLaurent Mazet <mazet@softndesign.org>
Thu, 13 Jun 2024 19:50:20 +0000 (21:50 +0200)
function.c
scrabble.c

index cec4f701d11a6610ec6f68df08122a3cb403aa0c..b0176c79f511722f15d9bf27916b9cca8b4dc556 100644 (file)
@@ -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);
     }
index d2d1b5a2e139e3a5fb327bd6a0b7f0afa477d73b..8c1e1d0816f097ffed6e62a5bd5eddde55b44329 100644 (file)
@@ -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: */