Я создаю метод для загрузки файла в связанный список. Это работает, но valgrind продолжает давать мне ошибку ниже. Я пытаюсь выделить память для new_node
... Я видел несколько сообщений, таких как one , в которых предлагается использовать calloc
, но это не сработало [функция загрузки остановлена за работой]. Я попытался инициализировать struct node * new_node = NULL;
, но у меня возникла та же проблема: при запуске valgrind возникла ошибка:
==1960== Uninitialised value was created by a heap allocation
==1960== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==1960== by 0x40112F: load (dictionary.c:85)
==1960== by 0x400964: main (speller.c:40)
==1960==
Может быть, у кого-нибудь есть безопасные способы выделить память, чтобы у меня не было неинициализированной переменной?
//HERE IS STRUCTURE OF HASHTABLE:
#include "dictionary.h"
// Represents number of buckets in a hash table
#define N 26
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
int countWords = 0;
//prototypes
void printNumber(); //struct node *start);
// Represents a hash table
// an array of nodes
node *hashtable[N];
node *head;
Ниже приведен актуальный раздел с ошибкой
bool load(const char *dictionary)
{
// Initialize hash table
for (int i = 0; i < N; i++)
{
hashtable[i] = NULL;
}
// Open dictionary
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
unload();
return false;
}
// Buffer for a word
char word[LENGTH + 1];
// Insert words into hash table
while (fscanf(file, "%s", word) != EOF)
{
// TODO
countWords++;
//create node
struct node * new_node;
//create a new node anytime new word
//create a node and allocate memory for each word
//THIS IS LINE 85 BELOW BY THE WAY!
new_node = (struct node *) malloc(sizeof(node));
//if empty...
if (new_node == NULL)
{
//speller quits
unload();
return false;
}
//copy word into node
strcpy(new_node->word, word);
//get location of word to go in hashtable by hashing value
int index = hash(word);
//put word in that location if nothing there
if(hashtable[index] == NULL)
{
//QUESTION: is head in array or at end of linked-list?
hashtable[index] = new_node;
}
//we need to link it to last node
else
{
// struct node * head = (struct node *) malloc(sizeof(node));
head = hashtable[index];
new_node -> next = head->next; //I may not be assigning this correct
head->next = new_node;
}
}
//printNumber();//header);
// free(new_node);
// Close dictionary
fclose(file);
// Indicate success
return true;
}
спасибо!