【发布时间】:2019-08-15 16:57:03
【问题描述】:
所以我知道还有其他人和我有同样的问题,但不幸的是我没有得到任何解决...所以基本上我正在哈希表中搜索一个键(基于给定的单词)如果没有找到返回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 库中的那个不起作用。
所以我试图做的是初始化变量,比如:
char *getWord;
getWord = strdup(ht_get(dict,word));
也喜欢:
char *getWord = ht_get(dict,word);
以及其他一些不起作用的方法。 抱歉问了这么长的问题。
【问题讨论】:
-
错误信息似乎清楚地表明
ht_get中的key是从一个未初始化的变量派生的,这意味着word是未初始化的。 -
"... strdup ... 在 string.h 库中不起作用。" 在什么意义上?
-
问题确实是这个词没有初始化!这让我发疯了,非常感谢您的帮助!