ошибка сегментации cs50 pset5 [загрузка текста в память с использованием таблицы ha sh] - PullRequest
0 голосов
/ 04 мая 2020

Я сейчас работаю над pset5 из cs50 .

Вся моя программа успешно компилируется, но останавливается в середине функции, называемой load, когда программа выполняется.

Ниже приведена моя функция load, и вы можете увидеть комментарий, в котором она выдала мне ошибку segmentation fault.

Если вы можете помочь мне выяснить, как мне следует подходить к моей ошибке, пожалуйста, дайте мне я знаю.
Я понимаю, что segmentation fault вызывается, когда программа пытается получить доступ к памяти, которая ей не принадлежит.
Однако я выделил память и проверил, достаточно ли памяти для продолжения работы программы .
Я предоставлю комментарии, чтобы подчеркнуть, что делает мой код.

// In another header file, I have defined 'LENGTH'
// Maximum length for a word
// (e.g., pneumonoultramicroscopicsilicovolcanoconiosis)
#define LENGTH 45

// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

// Hash table
// I have initialized the array of `node` pointer to point `NULL`
node *table[N] = {NULL};

unsigned int word_counter = 0;

bool load(const char *dictionary)
{
    // Open file, and if cannot open, return false
    FILE *file = fopen(dictionary, "r");
    if (file == NULL)
    {
        return false;
    }

    // read string in the file into array of character, `word` until reaching end of the file 
    char word[LENGTH + 1];
    while (fscanf(file, "%s", word) != EOF)
    {
        // keep track of how many word exists in the file, for later use (not in this function)
        word_counter += 1;

        // allocated memory for struct type `node`, if not enough memory found, return false 
        node *n = (node*)malloc(sizeof(node));
        if (n == NULL)
        {
            return false;
        }

        // assign index by hashing (hash function will not be posted in this question though.)
        unsigned int index = hash(&word[0]);
        // copy the word from file, into word field of struct type `node`
        strncpy(n->word, word, sizeof(word));

        // Access the node pointer in this index from array(table), and check is its `next` field points to NULL or not. 
        // If it is pointing to NULL, that means there is no word stored in this index of the bucket
        if (table[index]->next == NULL)    // THIS IS WHERE PROGRAM GIVES 'segmentation fault' !!!! :(
        {
            table[index]->next = n;
        }
        else
        {
            n->next = table[index];
            table[index]->next = n;
        }
    }
    return true;
}

1 Ответ

1 голос
/ 04 мая 2020

Вы определяете ant для инициализации таблицы ha sh следующим образом:

node *table[N] = {NULL};

Это означает, что у вас есть массив нулевых указателей.

Когда вы вставляете первое значение в таблицу тогда table[index] (для любой действительный индекс) будет нулевым указателем. Это означает, что table[index]->next попытайтесь разыменовать этот нулевой указатель, и у вас будет неопределенное поведение.

Сначала вам нужно проверить нулевые указатели:

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

table[index] = n;
...