Memory Checking with Valgrind#
Valgrind can find memory errors and memory leaks in C++ programs. It is most useful when a program compiles but crashes, behaves unpredictably, or uses dynamic memory.
The current course syllabus, assignment instructions, programming standards, and applicable CSN or college policies take precedence over anything on this website.
Compile first#
Compile with debugging information:
g++ -ggdb $CXXFLAGS main.cpp -o mainIf the program has multiple source files:
g++ -ggdb $CXXFLAGS main.cpp helper.cpp -o mainRun Valgrind#
Run the program under Valgrind:
valgrind ./mainFor a more detailed memory-leak report:
valgrind --leak-check=full --show-leak-kinds=all ./mainIf your program uses command-line arguments, put them after the program name:
valgrind --leak-check=full ./main input.txtWhat to look for#
Read the first error first. Later messages may be caused by the first problem.
Common Valgrind messages include:
| Message | Meaning |
|---|---|
Invalid read |
The program read memory it should not read. |
Invalid write |
The program wrote memory it should not write. |
Use of uninitialised value |
The program used a value before assigning to it. |
definitely lost |
The program leaked memory. |
For beginning programs, a clean run usually reports no memory errors and no definitely lost memory.
Good habits#
- Fix compiler warnings before using Valgrind.
- Use GDB first if the program crashes immediately and you need to find where.
- Use Valgrind when the problem involves memory, pointers, arrays, or dynamic allocation.
- Re-run Valgrind after each fix.
Valgrind output can be long. Save the command you ran and the first error message if you need help.