0

This is what valgrind is giving.

==7194== Invalid read of size 1
==7194==    at 0x4C2E0F4: strlen (in /usr/lib/valgrind/vgpreload_memcheck- amd64-linux.so)
==7194==    by 0x42278F: insert (tries.c:34)
==7194==    by 0x422393: load (dictionary.c:32)
==7194==    by 0x4208F2: main (speller.c:41)
==7194==  Address 0xadf5fcd is 0 bytes after a block of size 45 alloc'd
==7194==    at 0x4C2CC70: calloc (in /usr/lib/valgrind/vgpreload_memcheck-   amd64-linux.so)
==7194==    by 0x4223FE: load (dictionary.c:36)
==7194==    by 0x4208F2: main (speller.c:41)

The dictionary.c:36 refers to "word =calloc(LENGTH,sizeof(char));" in following piece of code.

bool load(const char *dictionary)
{
   my_trie = getNode();
   char* word =calloc(LENGTH,sizeof(char));
   int i=0;
   FILE *file = fopen(dictionary, "r");
   if (file == NULL)
   {
       printf("Could not open %s.\n", dictionary);
       return false;
   }

   for (int c = fgetc(file); c != EOF; c = fgetc(file)){
        if(c == '\n'){
            insert(my_trie, word);
            size_of_dictionary++;
            i=0;
            free(word);
            word =calloc(LENGTH,sizeof(char));  // This is dictionary.c:36
         }
       else{
           *(word+i)=c;
           i++;
       }
 }
   free(word);
   return true;
}
1
  • It looks more like the issue is at tries.c:34, not in the load function. Without seeing all of the code to duplicate the problem, I can't really tell what the problem is.
    – Cliff B
    Commented Jul 9, 2018 at 1:52

1 Answer 1

1

As Cliff noted, we can only guess unless you show the code for insert. But here's something I found:

You allocate LENGTH bytes. But with the last byte of a C-style string being the null terminator, you can use that only to store a string of length LENGTH-1. Which means you should have one more byte.

You free and re-calloc the space for the word. I hope you strcpy (or similar) within insert? If so, you wouldn't need to throw away the memory if you just set the null terminator with a *(word+i)=0; before insert(my_trie,word); instead of relying on calloc.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .