"Uninitialised value was created by a stack allocation" 在 C++ 中 std::map

"Uninitialised value was created by a stack allocation" in c++ std::map

本文关键字:C++ std map allocation stack value Uninitialised was created by      更新时间:2023-10-16

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]=''但这似乎不会影响代码的其余部分。

现在我用从文件(包含键和值行列表)中获取的条目填充映射。键的尺寸始终较长。

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 。除非您明确地将未初始化的double放入其中,否则无法从Map[Key]中获得未初始化的double(即使KeyMap中不存在,它也将使用double()初始化)。这可能指向__printf_fp()实现中的一段有趣的代码:我会用一个简单的测试程序来验证这份报告是否确实可以使用以下内容进行复制:

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

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