简体   繁体   中英

Getting segmentation fault. Invalid memory write of size 1 on Valgrind (CS50 PSET5 Speller)

Can't seem to make Valgrind happy.

Valgrind Result:

==21003== Invalid write of size 1 ==21003== at 0x4C32E0D: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==21003== by 0x40125E: load (dictionary.c:111) ==21003== by 0x400964: main (speller.c:40)

Invalid write of size 8 ==22741== at 0x40123E: load (dictionary.c:107) ==22741== by 0x400964: main (speller.c:40) ==22741== Address 0x55cd9a0 is 32 bytes before an unallocated block of size 4,183,584 in arena "client"

Problem seems to be in line 110 which is StrCpy in my bool LOAD. Code as below - I can't understand why there's an invalid write of size 1.

Another one is n -> next = table[hashInt];

I don't understand why I am getting invalid write.

bool load(const char *dictionary)
{

    FILE *file = fopen(dictionary, "r");

    if (file == NULL)
    {
        printf("error opening file");
        return 1;
    }

    char word [LENGTH + 1];

    while (fscanf(file, "%s\n", word) != EOF)
    {

        int hashInt = hash(word);

        node *n = malloc(sizeof(n));

        if (n == NULL)
        {
            unload();
            return 1;
        }

        if (table[hashInt] == NULL)
        {
            table[hashInt] = n;
        }
        else
        {
            n -> next = table[hashInt];
            table[hashInt] = n;
        }

        strcpy(n -> word, word);
        wordLoaded++;
    }
    fclose(file);
    return 0;
}

This node *n = malloc(sizeof(n)); is probably a typo. Did you mean sizeof(node) ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM