首页 > 解决方案 > 如何修复 Valgrind“条件跳转...”错误

问题描述

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

所以这里是 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 库中的那个不起作用。

所以我试图做的是初始化变量liek:

字符 * 获取单词;
getWord = strdup(ht_get(dict,word));

以及:

char *getWord = ht_get(dict,word);

以及其他一些不起作用的方法。对不起,很长的问题。

标签: cdebuggingvalgrind

解决方案


仔细检查这三行时:

==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
...

既然key是 的第二个参数ht_get并被传递给_strdup,那么结论就是word未初始化。

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

如果遇到的第一个字符是单词分隔符,您的逻辑缺陷将word是未初始化。

一种可能的解决方法是建立一个标志来指示您是否创建了一个单词。该标志被初始化falsetrue在形成单词时变为,并且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;
    }
...

推荐阅读