Pset5(Speller)无内存泄漏却触发Valgrind未初始化值错误求助
Let's break down the root cause of your Valgrind warning first:
The error points to this line in your check function:
lower[i] = tolower(word[i]);
Your current loop runs fixed LENGTH + 1 times, but the input word is a null-terminated C string—most words will be shorter than LENGTH (which is 45 for Pset5). When i exceeds the actual length of word (after hitting the \0 terminator), you're still reading from word[i], and those memory positions are uninitialized. Valgrind flags this because it detects you're using uninitialized data in subsequent operations (like passing lower to your hash function).
How to Fix It
Instead of looping through all LENGTH + 1 positions, only iterate until you hit the null terminator of word, then explicitly terminate the lower array to keep it a valid C string:
bool check(const char *word) { char lower[LENGTH + 1]; int i = 0; // Convert only the actual characters in word to lowercase while (word[i] != '\0') { lower[i] = tolower(word[i]); i++; } // Ensure the lowercase string is properly null-terminated lower[i] = '\0'; node *tmp = table[hash(lower)]; while (tmp != NULL) { // Since tmp->word is lowercase, we can use strcmp instead of strcasecmp for efficiency if (strcmp(lower, tmp->word) == 0) { return true; } tmp = tmp->next; } return false; }
A bonus optimization: since your dictionary stores all lowercase words, using strcmp(lower, tmp->word) instead of strcasecmp(word, tmp->word) avoids redundant case checking and is faster.
Quick Side Note
Your size function has a logical error that might cause unexpected behavior later:
if (&load == false) { return '0'; }
Comparing the function pointer &load to false doesn't make sense. Instead, use your global count variable to check if the dictionary was loaded—if count == 0, return 0 (as an integer, not the character '0'):
unsigned int size(void) { return count; }
Because count starts at 0 and only increments during a successful load, this correctly returns 0 when no words are loaded, and the actual count otherwise.
内容的提问来源于stack exchange,提问作者Bunnycorn

