如何修复 Valgrind "Conditional Jump..." 错误

How to fix Valgrind "Conditional Jump..." error

所以我知道还有其他人和我有同样的问题,但不幸的是我没有得到任何解决......所以基本上我正在搜索哈希表中的键(基于给定的词)如果没有发现 return NULL,但如果发现 return 值。它会不断重复,直到读取的文件中没有更多单词。

所以这是 valgrind 的输出。

    ==877683== Conditional jump or move depends on uninitialised 
    value(s)
    ==877683==    at 0x4C31258: __strlen_sse2 (in 
    /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==877683==    by 0x401641: _strdup (loesung.c:58)
    ==877683==    by 0x401641: ht_get (loesung.c:212)
    ==877683==    by 0x400E5C: main (loesung.c:513)
    ==877683==  Uninitialised value was created by a stack 
    allocation
    ==877683==    at 0x400B0A: main (loesung.c:325)

这里是一些代码...

    while((c = fgetc(input)) != EOF) {
        if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')){   
                ...
        }
        else if(c == 10 || (c >= 32 && c <= 64) || (c >= 91 && c <= 
    96) || (c >= 123 && c <= 126)){
            if(ht_get(dict,word) == NULL){....}         //LINE 513


   int main(int argc, char *argv[]){  //LINE 325 Where the value 
                                        was created apparently... I 
                                        dont get this at all!
   if(argc != 2){
     fprintf(stderr,"...");
     exit(2);
     return 2;
   }
   else {
     wb = fopen(argv[1], "r");
   }

这里是函数 ht_get...

    char *ht_get(HashTable *hashtable, const char *key){
    char *key_cp = NULL;
    unsigned int i = 0;
    List *tmp;

    key_cp = _strdup(key);              //LINE 212
    i = hash(key, hashtable->size);
    tmp = hashtable->array[i];

    while (tmp != NULL) {
            if (str_cmp1(tmp->key, key_cp) == 0) { 
                    break;
            }
            tmp = tmp->next;
    }
    free(key_cp);

    if (tmp == NULL) {
            return NULL;
    }
    return tmp->value;
    }

而_strdup 函数与strdup 相同,但我必须自己编写它,因为string.h 库中的函数不起作用。

所以我尝试做的是初始化变量,如下所示:

char * getWord;
getWord = strdup(ht_get(dict,word));

以及喜欢:

char *getWord = ht_get(dict,word);

以及其他一些行不通的方法。 很抱歉问了这么长的问题。

仔细检查这三行时:

==877683==    by 0x401641: _strdup (loesung.c:58)
==877683==    by 0x401641: ht_get (loesung.c:212)
==877683==    by 0x400E5C: main (loesung.c:513)

从您的代码片段中:

...
    key_cp = _strdup(key);              //LINE 212
...
            if(ht_get(dict,word) == NULL){....}         //LINE 513
...

Since key is the second parameter to ht_get and is passed to _strdup, then the conclusion is that word is uninitialized.

虽然您没有显示所有代码,但很可能您正在构建 word,直到遇到单词分隔符,然后调用 ht_get

Your logical flaw would be that word is not initialized if the very first character encountered is a word separator.

一个可能的修复方法是建立一个标志来指示您是否创建了一个词。标志被初始化 false 并在形成单词时变为 true,并且在处理单词分隔符时变为 false

bool have_word = false;
...
while ((c = fgetc(input)) != EOF) {
    if (isalpha(c)) {
        ... make a word
        have_word = true;
    } else {
        if (have_word) {
            ... process a word
        }
        have_word = false;
    }
...