c++ - C++ std::map 中的 "Uninitialised value was created by a stack allocation"

标签 c++ dictionary std valgrind

Valgrind 告诉我我的代码中有错误,但我找不到它... 这是一个代码片段:

22 int main(int argc, char *argv[]){
...
//argv[1] contains the name of a file
int length=atoi(argv[2]);
map<string, double> Map;
char* Key;
Key = new char [length+1];
...

我还使用了 Key[length]='\0' 但这似乎不会影响其余代码。

现在我用从文件中获取的条目填充映射(其中包含键和值行的列表。键的维度总是小于长度。

while( file_stream >> Key >> Value){
Map[Key]=Value;
....
}

此时,我调用:

cout << Key  << " has value ";
159   cout << Map[Key] << endl;

程序编译和执行都很好,但是 Valgrind 给出了很多这种类型的错误:

==6921== Conditional jump or move depends on uninitialised value(s)
==6921==    at 0x56274A0: __printf_fp (printf_fp.c:404)
==6921==    by 0x562396A: vfprintf (vfprintf.c:1622)
==6921==    by 0x5648C81: vsnprintf (vsnprintf.c:120)
==6921==    by 0x4EB64AE: ??? (in /usr/lib/libstdc++.so.6.0.13)
==6921==    by 0x4EB9002: std::ostreambuf_iterator<char, std::char_traits<char> > std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::_M_insert_float<double>(std::ostreambuf_iterator<char, std::char_traits<char> >, std::ios_base&, char, char, double) const (in /usr/lib/libstdc++.so.6.0.13)
==6921==    by 0x4EB9328: std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::do_put(std::ostreambuf_iterator<char, std::char_traits<char> >, std::ios_base&, char, double) const (in /usr/lib/libstdc++.so.6.0.13)
==6921==    by 0x4ECCC9E: std::ostream& std::ostream::_M_insert<double>(double) (in /usr/lib/libstdc++.so.6.0.13)
==6921==    by 0x40366E: main (MyProgram.cpp:159)
==6921==  Uninitialised value was created by a stack allocation
==6921==    at 0x401C61: main (MyProgram.cpp:22)

你有什么线索吗?我宁愿不发布所有长代码(请不要为此责备)

谢谢!!

最佳答案

堆栈跟踪表明您正在格式化一个double。无法从 Map[Key] 中获取未初始化的 double ,除非您明确地将未初始化的 double 插入其中(即使是 >Key 不存在于 Map 中,将使用 double() 初始化。这可能指向 __printf_fp() 实现中的一段有趣代码:我将使用一个简单的测试程序验证该报告是否确实可以使用以下方法重现:

#include <iostream>
int main() {
    std::cout << 3.14;
}

...如果是这样,我将忽略 valgrind 的报告。在一个非常平静的下午,可能需要深入研究 __printf_fp() 的实现,以找到它在哪里做了一些有问题的事情,并确定它是否真的重要(我不会赌我身上发生过的事情,虽然:我宁愿自己实现浮点格式化,但是,这可能需要一个下午以上的时间,因为它显然不重要)。

关于c++ - C++ std::map 中的 "Uninitialised value was created by a stack allocation",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19201518/

相关文章:

c++ - 如何在 QScintilla 编辑器小部件中取消选择/取消突出显示选定和突出显示的文本?

python - 从 {index : list of row values} 形式的字典构造 Pandas DataFrame

python - 什么是 python 字典和 zip 的最佳 C++ 替代品?

c++ - 使用 Range v3 范围,如何将 View 和操作组合到一个管道中?

c++ - 无法编译 QtCreator

c++ - 使用幻灯片而不是交换进行冒泡排序

c++ - 编译大型头文件 C++

python - 询问用户列表的索引,Python

c++ - 在结构的 c++ std vector 中搜索具有匹配字符串的结构

c++ - std::stringstream 运算符 << 使用 strcat 吗?