Web Analytics Made
Easy - StatCounter

Bash: writing the output and errors to a file, some Valgrind.

I’m calling a program that I wrote, so it is under development and uses some print debugging. When I have runtime errors I can’t figure out, I use Valgrind. Valgrind works well for finding memory leaks and indexing problems, but it is slow and has a lot of output. So I want to capture all of the output and error messages from Valgrind and the program all in one text file, so I can search and trace what happened.

First, to redirect the output and errors to a file, the format is 2>&1, which I usually mix up:

command > output.txt 2>&1

A variation suggested by Dmytro Mishkin, which allows you to see the output on the screen as well as write everything to file, is:

command 2>&1 | tee -a log.txt

This post has many of the permutations of redirecting output and errors to files.

Ok, so doing so with Valgrind, my usual process, after mixing up the --leak-check flag (I have trouble remembering this value is yes), is

valgrind --leak-check=yes ./program-name args > output.log 2>&1

Valgrind takes a long time to run. If I am able to reproduce the runtime error with a smaller dataset, I will, to reduce the time for the Valgrind run.

The reason for the long Valgrind runtime is explained in the manual:

Regardless of which tool is in use, Valgrind takes control of your program before it starts. Debugging information is read from the executable and associated libraries, so that error messages and other outputs can be phrased in terms of source code locations, when appropriate.

Your program is then run on a synthetic CPU provided by the Valgrind core. As new code is executed for the first time, the core hands the code to the selected tool. The tool adds its own instrumentation code to this and hands the result back to the core, which coordinates the continued execution of this instrumented code.

The amount of instrumentation code added varies widely between tools. At one end of the scale, Memcheck adds code to check every memory access and every value computed, making it run 10-50 times slower than natively. At the other end of the spectrum, the minimal tool, called Nulgrind, adds no instrumentation at all and causes in total “only” about a 4 times slowdown.

© Amy Tabb 2018 - 2021. All rights reserved. The contents of this site reflect my personal perspectives and not those of any other entity.