i need to make a function which creates a hash table with chaining method, after this error occurred i continued to the next task for now , and while doing a loop to read lines from text file, after 2 or 3 iterations i get an error "Critical error detected c0000374" i can't find any reason for it and i searched the web of course didn't find what was the problem here's my code:
int parseWordsToTable(char* filePath, HashTable* ht) {
FILE* Dictionary = fopen(filePath, "r");
for (int Line = 0; Line < 50; Line++) {
char* line = (char*)malloc(sizeof(char));
if (line == NULL)
exit("Not Enough Memory!");
fgets(line, 15, Dictionary);
printf("%s", line);
}
return 1;
}
sometimes it gets 2 iterations and sometimes 3 , i just don't get it... the breakpoint and the error occur on this line:
char* line = (char*)malloc(sizeof(char));
by the way , the same happens on this code:
HashTable* initTable(int tableSize, int hashFunction) {
HashTable* Table = (HashTable*)malloc(sizeof(HashTable));
if (Table == NULL)
exit("Not Enough Memory!");
Table->tableSize = tableSize;
Table->cellsTaken = 0;
Table->hashFunction = hashFunction;
Table->numOfElements = 0;
for (int index = 0; index < tableSize; index++) {
Table[index].hashTable = (HashTableElement*)malloc(sizeof(HashTableElement));
if (Table[index].hashTable == NULL)
exit("Not Enough Memory!");
Table[index].hashTable->key = index;
Table[index].hashTable->chain = (LinkedList*)malloc(sizeof(LinkedList));
if (Table[index].hashTable->chain == NULL)
exit("Not Enough Memory!");
Table[index].hashTable->key = 0;
Table[index].hashTable->chain = NULL;
}
return Table;
}
but only on the fourth iteration..
You must allocate enough elements. It is bad to lying for fgets()
that 15-byte buffer is passed while the buffer is actually only one byte.
Also don't forget to check if fopen()
is successful and close the opened file.
int parseWordsToTable(char* filePath, HashTable* ht) {
FILE* Dictionary = fopen(filePath, "r");
if (Dictionary == NULL) return 0; /* check if fopen() is successful */
for (int Line = 0; Line < 50; Line++) {
char* line = (char*)malloc(15); /* allocate enough elements */
if (line == NULL)
exit("Not Enough Memory!");
fgets(line, 15, Dictionary);
printf("%s", line);
}
fclose(Dictionary); /* close opened file */
return 1;
}