gpt4 book ai didi

c - Valgrind 未初始化值(制作链表数据结构)

转载 作者:太空狗 更新时间:2023-10-29 15:42:22 25 4
gpt4 key购买 nike

我已经创建了一个链表类,但是这个函数正在产生 valgrind 错误,因为它说在这个函数中有一个基于未初始化值的条件跳转。我不确定我需要做什么来修复它。

本质上,链表有一个节点类,它遍历所有节点,检查关键参数是否与预先存在的节点匹配,如果匹配则返回值。

const char *dictionary_get(dictionary_t *d, const char *key)
{

node* current;
current = d->head;
if(strcmp(current->key,key)==0)
return current->value;
while(current->next != NULL){
current = current->next;
if(current!=NULL && strcmp(current->key,key)==0)
return current->value;
}

return NULL;
}

有什么想法吗?


我重新检查了 valgrind 跟踪源,这是输出:

==25042== Conditional jump or move depends on uninitialised value(s)
==25042== at 0x4A06E6A: strcmp (mc_replace_strmem.c:412)
==25042== by 0x400DD6: dictionary_get (libdictionary.c:143)
==25042== by 0x400826: main (part2.c:84)
==25042== Uninitialised value was created by a stack allocation
==25042== at 0x400AE3: dictionary_parse (libdictionary.c:69)
==25042==
==25042== Conditional jump or move depends on uninitialised value(s)
==25042== at 0x4A06E8A: strcmp (mc_replace_strmem.c:412)
==25042== by 0x400DD6: dictionary_get (libdictionary.c:143)
==25042== by 0x400826: main (part2.c:84)
==25042== Uninitialised value was created by a stack allocation
==25042== at 0x400AE3: dictionary_parse (libdictionary.c:69)
==25042==
==25042== Conditional jump or move depends on uninitialised value(s)
==25042== at 0x400DD9: dictionary_get (libdictionary.c:143)
==25042== by 0x400826: main (part2.c:84)
==25042== Uninitialised value was created by a stack allocation
==25042== at 0x400AE3: dictionary_parse (libdictionary.c:69)

看起来这可能来自 dictionary_parse,所以我也会发布该函数。

int dictionary_parse(dictionary_t *d, char *key_value)
{
char* colon;
char* space;
colon = key_value;
space = key_value;

space++;

int key_length = -1; //Default key length to check for failure

int i=0;
int j=0; // Loop variables
int k=0;

int length = strlen(key_value);

for(i=0;i<length-2;i++){
if(*colon == ':' && *space == ' '){
key_length = i;
break;
}
colon++;
space++;
}

if(key_length == -1 || key_length == 0)
return -1;

int value_length = length-2-key_length;

colon = key_value;


char key_word[key_length];
key_word[0] = '\0';
char value_word[value_length];
value_word[0] = '\0';

for(j=0;j<key_length;j++){
key_word[j] = *colon;
colon++;
}

space++;

for(k=0; k<value_length;k++){
value_word[k] = *space;
space++;
}
char* finalkey[key_length];
strcpy((char*)finalkey,key_word);
char* finalvalue[value_length];
strcpy((char*)finalvalue,value_word);

dictionary_add(d,(char*)finalkey,(char*)finalvalue);

return 0;
}

最佳答案

像这样的线条

char key_word[key_length];

看起来非常可疑。

我不知道你接下来用这些做什么,但是为那些应该比函数调用持续时间更长的东西创建一个临时的可变长度数组似乎很奇怪。

此外,可变长度数组不包括终止符 '\0'

关于c - Valgrind 未初始化值(制作链表数据结构),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3646848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com