You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pset5(Speller)无内存泄漏却触发Valgrind未初始化值错误求助

Fixing Valgrind's "Conditional jump or move depends on uninitialised value(s)" in Pset5's check Function

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 21:02:29