Reputation: 14997
I'm using Microsoft Visual C++ 6.0 and trying to debug someone else's program. I tried to use printf statements but for some reason, these statements are not shown on the screen as the program runs. I am able to use fprintf to print these statements to file, but this is useless when the program crashes in the middle of execution, as the file would be empty then.
How can I force some output to screen?
Upvotes: 1
Views: 3402
Reputation: 1100
To force output to the screen, please see the first section below. The second and third options below are also good for debugging program crashes like these.
Using printf with fflush (refinement of Vishal Kumar's answer)
Vishal Kumar's answer worked for me, but I had to do a little research to find out how to use fflush. I had a problem where my program was crashing "in the middle" of a printf statement which did not make sense. Here is my refinement of his answer. In cases where a debugger is difficult to use (e.g. multithreading), you can use fflush after every printf (or fprintf) statement. For example, "pepper your code" with:
... // code
printf("Part 1 executed successfully");
fflush(stdout); // flushes the stdout buffer
... // further code
printf("Part 2 executed successfully");
fflush(stdout);
... // repeat as necessary
Run, observe the output, and put more print statements between the last statement that prints, and the first statement that doesn't print, until you isolate the problem.
Debugger
If you are able to use a debugger, it is a more efficient choice than peppering your code with output statements as described above, but there are cases where you have to resort to that.
Valgrind
If you are using Linux (which I gather you are not because it is in MS Visual C++), valgrind is another option to see where your code is crashing (and for detecting memory leaks). If your code is compiled for debug, if your program is called "myProgram", you can just call from the terminal window as follows:
valgrind myProgram
Upvotes: 3