1

Valgrind gives me this:

==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

How do I find where this bug is in my code if it does not point to any line?

I compiled with g++ on a Linux instance in AWS.

EDIT

Okay it seems that somehow I've left the program in an invalid state regarding the streams (thanks) after returning from main. I do make calls to

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

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

Is there anything I need to do here to clean up before returning from main?

shane
  • 1,742
  • 2
  • 19
  • 36
  • Did you somehow explicitly destroy `std::cout` (or any other `std::ostream` with static storage duration) or did anything else weird with it? – Baum mit Augen Sep 16 '15 at 18:43
  • Use functions returning a global, to ease the global initialization fiasco. –  Sep 16 '15 at 18:43
  • I did call `std::ofstream out(argv[2]); std::cout.rdbuf(out.rdbuf());` – shane Sep 16 '15 at 18:44

1 Answers1

2

It is actually triggered by the exit: your main function finished its job and the program is in cleanup phase, such as calling destructors on global objects and closing streams.

The bug itself is most likely somewhere earlier in your code, leaving the program in some invalid state that becomes an issue only at the end.


In your comments you say that you change the cout's stream buffer to your own thing. Did you set it back to the default afterwards? Otherwise, at the end of main, when the program tries to flush the std::cout it may access the stream buffer that does not exist anymore.

See the example at: http://www.cplusplus.com/reference/ios/ios/rdbuf/

CygnusX1
  • 20,968
  • 5
  • 65
  • 109