Hello i am doing a project where i have to implement a hashTable that stores words based on a hash function. On a stress test i get malloc(): memory corruption
The initial declaration of the hashTable
hashTable = (char**)malloc(hashSize[0] * sizeof(char*));
This is the function i wrote to add word to hashTable of hashSize:
void addWord(char** hashTable, unsigned int hashSize, const char* word) {
int bucketIndex = hash(word, hashSize);
//printf("Word to add = %s, bucket = %d, hashTable size = %d\n", word, bucketIndex, hashSize);
if(hashTable[bucketIndex] == NULL) {
hashTable[bucketIndex] = (char*)malloc(strlen(word) * sizeof(char));
strcpy(hashTable[bucketIndex], word);
return;
}
/* checks for duplicats */
int exists = 0;
char* heyStack = (char*)malloc(strlen(hashTable[bucketIndex]));
memcpy(heyStack, hashTable[bucketIndex], strlen(hashTable[bucketIndex]));
char* token = strtok(heyStack, " ");
while(token) {
if(strcmp(token, word) == 0) {
exists = 1;
break;
}
token = strtok(NULL, " ");
}
/* end check for duplicates */
if(exists == 0) {
size_t bucketSize = strlen(hashTable[bucketIndex]);
hashTable[bucketIndex] = (char*)realloc(hashTable[bucketIndex], bucketSize + strlen(word) + 2);
memcpy(hashTable[bucketIndex] + bucketSize, " ", 1);
memcpy(hashTable[bucketIndex] + bucketSize + 1, word, strlen(word) + 1);
}
}
I have a stress test that adds 20k words to the table and it always breaks on the same word (no 10k something)
Any ideas on what i am doing wrong ?
Tyvm