解决未指向我的代码的 valgrind 内存错误

Solving valgrind memory error not pointing to my code

Valgrind 给我这个:

==26348== Invalid read of size 8
==26348==    at 0x4EC3DA8: std::ostream::flush() (in /usr/lib64/libstdc++.so.6.0.19)
==26348==    by 0x4E9E477: std::ios_base::Init::~Init() (in /usr/lib64/libstdc++.so.6.0.19)
 ==26348==    by 0x5684E58: __run_exit_handlers (in /lib64/libc-2.17.so)
==26348==    by 0x5684EA4: exit (in /lib64/libc-2.17.so)
==26348==    by 0x566DAFB: (below main) (in /lib64/libc-2.17.so)
==26348==  Address 0xffefffd98 is just below the stack ptr.  To suppress, use: --workaround-gcc296-bugs=yes

如果这个错误没有指向任何行,我如何找到它在我的代码中的位置?

我在 AWS 的 Linux 实例上用 g++ 编译。

编辑

好吧,从 main 返回后,我似乎以某种方式让程序处于关于流的无效状态(谢谢)。我打电话给

std::ifstream in(argv[1]);
std::cin.rdbuf(in.rdbuf());

std::ofstream out(argv[2]);
std::cout.rdbuf(out.rdbuf());

在从 main 返回之前,我需要在这里做些什么来清理吗?

它实际上是由退出触发的:您的主函数完成了它的工作并且程序处于清理阶段,例如对全局对象调用析构函数并关闭流。

错误本身很可能出现在您代码的较早位置,使程序处于某种无效状态,只有在最后才成为问题。


在您的评论中,您说您将 cout 的流缓冲区更改为您自己的东西。是不是后来改回默认了? 否则,在 main 结束时,当程序尝试 flush std::cout 时,它可能会访问不再存在的流缓冲区。

查看示例:http://www.cplusplus.com/reference/ios/ios/rdbuf/