==2630== Conditional jump or move depends on uninitialised value(s)
==2630== at 0x4E82D71: vfprintf (in /usr/lib64/libc-2.21.so)
==2630== by 0x4E88E78: printf (in /usr/lib64/libc-2.21.so)
==2630== by 0x400C0C: searchWord (T9.c:91)
==2630== by 0x400A0A: main (T9.c:40)
==2114== Uninitialised value was created by a heap allocation
==2114== at 0x4C28C50: malloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==2114== by 0x400FD1: newStr (trie_node.c:125)
==2114== by 0x400F8C: create_trie (trie_node.c:117)
==2114== by 0x4009D5: main (T9.c:37)
我在 valgrind 中运行跟踪函数时收到上面的错误消息。我很确定我已经初始化了该变量。 这是结构代码:
struct wordList* newStr(char* text) {
char* word;
struct wordList* tmp = (struct wordList*)malloc(sizeof(struct wordList));
word = (char *)malloc(sizeof(char) * strlen(text) + 1);
strncpy(word, text, strlen(text));
tmp->str = word;
tmp->next = NULL;
return tmp;
}
T9.c 第 91 行周围的代码:
struct wordList* cur;
if (cur && invalid == 0 && flag == 0) {
printf("\t\'%s\'\n", cur->str);
}
更新:
我修改了 strncpy 行
strncpy(word, text, strlen(text));
到
word = strncpy(word, text, strlen(text));
这解决了未初始化的问题,但是我收到了我不明白的新错误消息:
==3245== Invalid read of size 1
==3245== at 0x4E82D71: vfprintf (in /usr/lib64/libc-2.21.so)
==3245== by 0x4E88E78: printf (in /usr/lib64/libc-2.21.so)
==3245== by 0x400C0C: searchWord (T9.c:91)
==3245== by 0x400A0A: main (T9.c:40)
==3245== Address 0x51f7d45 is 0 bytes after a block of size 5 alloc'd
==3245== at 0x4C28C50: malloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==3245== by 0x400FC1: newStr (trie_node.c:124)
==3245== by 0x400F80: create_trie (trie_node.c:117)
==3245== by 0x4009D5: main (T9.c:37)
最佳答案
我需要查看更多代码,但是虽然我不确定这正是 valgrind 所提示的内容,但您的代码确实存在一个重大错误:
strncpy(word, text, strlen(text));
您没有以空终止字符串,您只是复制实际字符。这特别有趣,因为有一个函数已经负责分配正确的内存量和复制字符串: strdup
.
还强制警告停止转换 malloc
的返回值。
关于c - 来自 valgrind 的未初始化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33686952/