Note: Valgrind is Linux only. If you aren't running Linux, or want a tool designed from the start to make debugging segfaults and memory issues easier, check out Cee Studio, a fully online C and C++ development environment from our sponsor. Cee Studio provides instant and informative feedback on memory issues.
May 11, 2019 Valgrind 原理 valgrind 是一个提供了一些 debug 和优化的工具的工具箱,可以使得你的程序减少内存泄漏或者错误访问. Valgrind 默认使用 memcheck 去检查内存问题. Valgrind reports 4 blocks lost - those are the four names we forgot to free.They are still reachable because their pointers are still in the lines array. For a clean run of valgrind, as expected in all your CS50 labs, the program would need to actually free every block of memory it allocates.
Valgrind is a multipurpose code profilingand memory debugging tool for Linux when on the x86 and, as of version 3,AMD64, architectures. Itallows you to run your program in Valgrind's own environment that monitorsmemory usage such as calls to malloc and free (or new and delete in C++). Ifyou use uninitialized memory, write off the end of an array, or forget to freea pointer, Valgrind can detect it. Since these are particularly commonproblems, this tutorial will focus mainly on using Valgrind to find thesetypes of simple memory problems, though Valgrind is a tool that can do a lotmore.
Alternatively, for Windows users who wantto develop Windows-specific software, you might be interested in IBM's Purify, which hasfeatures similar to Valgrind for finding memory leaks and invalid memoryaccesses. A trial download is available.

Getting Valgrind
If you're running Linux and you don't have a copy already, you can getValgrind from the Valgrinddownload page.Installation should be as simple as decompressing and untarring using bzip2(XYZ is the version number in the below examples)which will create a directory called valgrind-XYZ; change into that directoryand runNow that you have Valgrind installed, let's look at how to use it.
Finding Memory Leaks With Valgrind
Memory leaks are among the most difficult bugs to detect because they don'tcause any outward problems until you've run out of memory and your call tomalloc suddenly fails. In fact, when working with a language like C or C++that doesn't have garbage collection, almost half your time might be spenthandling correctly freeing memory. And even one mistake can be costly ifyour program runs for long enough and follows that branch of code.When you run your code, you'll need to specify the tool you want to use;simply running valgrind will give you the current list. We'll focus mainly onthe memcheck tool for this tutorial as running valgrind with the memcheck toolwill allow us to check correct memory usage. With no other arguments, Valgrind presents a summary of calls to free andmalloc: (Note that 18490 is the process id on my system; it will differbetween runs.)If you have a memory leak, then the number of allocs and the number of freeswill differ (you can't use one free to release the memory belonging to morethan one alloc). We'll come back to the error summary later, but for now,notice that some errors might be suppressed -- this is because some errorswill be from standard library routines rather than your own code.
If the number of allocs differs from the number of frees, you'll want to rerunyour program again with the leak-check option. This will show you all of thecalls to malloc/new/etc that don't have a matching free.
For demonstration purposes, I'll use a really simple program that I'll compileto the executable called 'example1'This will result in some information about the program showing up, culminatingin a list of calls to malloc that did not have subsequent calls to free:This doesn't tell us quite as much as we'd like, though -- we know that thememory leak was caused by a call to malloc in main, but we don't have the linenumber. The problem is that we didn't compile using the -g option of gcc,which adds debugging symbols. So if we recompile with debugging symbols, weget the following, more useful, output:Now we know the exact line where the lost memory was allocated. Although it'sstill a question of tracking down exactly when you want to free that memory,at least you know where to start looking. And since for every call to mallocor new, you should have a plan for handling the memory, knowing where thememory is lost will help you figure out where to start looking.
There will be times when the --leak-check=yes option will not result inshowing you all memory leaks. To find absolutely every unpaired call to freeor new, you'll need to use the --show-reachable=yes option. Its output isalmost exactly the same, but it will show more unfreed memory.
Finding Invalid Pointer Use With Valgrind
Valgrind can also find the use of invalid heap memory using the memcheck tool.For instance, if you allocate an array with malloc or new and then try toaccess a location past the end of the array:Valgrind will detect it. For instance, running the following program,example2, through Valgrindwithresults in the following warningWhat this tell us is that we're using a pointer allocated room for10 bytes, outside that range -- consequently, we have an 'Invalid write'. Ifwe were to try to read from that memory, we'd be alerted to an 'Invalid readof size X', where X is the amount of memory we try to read. (For a char,it'll be one, and for an int, it would be either 2 or 4, depending on yoursystem.)As usual, Valgrind prints the stack trace of function calls so that we knowexactly where the error occurs.Detecting The Use Of Uninitialized Variables
Another type of operation that Valgrind will detect is the use of anuninitialized value in a conditional statement. Although you should be in thehabit of initializing all variables that you create, Valgrind will help findthose cases where you don't. For instance, running the following code asexample3through Valgrind will result in Valgrind is even smart enough to know that if a variable is assigned the valueof an uninitialized variable, that that variable is still in an'uninitialized' state. For instance, running the following code:in Valgrind as example4 results in the following warning:You might think that the problem was in foo, and that the rest of the callstack probably isn't that important. But since main passes in anuninitialized value to foo (we never assign a value to y), it turns out thatthat's where we have to start looking and trace back the path of variableassignments until we find a variable that wasn't initialized.
This will only help you if you actually test that branch of code, and inparticular, that conditional statement. Make sure to cover all executionpaths during testing!
What else will Valgrind Find
Valgrind will detect a few other improper uses of memory: if you call freetwice on the same pointer value, Valgrind will detect this for you; you'll getan error:along with the corresponding stack trace.Valgrind also detects improperly chosen methods of freeing memory. Forinstance, in C++ there are three basic options for freeing dynamic memory:free, delete, and delete[]. The free function should only be matched with acall to malloc rather than a call to, say, delete -- on some systems, you might be able to get away with notdoing this, but it's not very portable. Moreover, the delete keyword should only be paired with the new keyword (for allocation of single objects), and the delete[] keyword should only bepaired with the new[] keyword (for allocation of arrays). (Though some compilers will allow you to get away with using the wrong version of delete,there's no guarantee that all of them will. It's just not part of thestandard.)
If you do trigger one of these problems, you'll get this error: which really should be fixed even if your code happens to be working.
What Won't Valgrind Find?
Valgrind doesn't perform bounds checking on static arrays (allocated on thestack). So if you declare an array inside your function:then Valgrind won't alert you! One possible solution for testing purposes issimply to change your static arrays into dynamically allocated memory takenfrom the heap, where you will get bounds-checking, though this could be a messof unfreed memory.A Few More Caveats
What's the drawback of using Valgrind? It's going to consume more memory --up to twice as much as your program normally does. If you're testing anabsolutely huge memory hog, you might have issues. It's also going to takelonger to run your code when you're using Valgrind to test it. This shouldn'tbe a problem most of the time, and it only affects you during testing. But ifyou're running an already slow program, this might affect you.Finally, Valgrind isn't going to detect every error you have -- if you don'ttest for buffer overflows by using long input strings, Valgrind won't tell youthat your code is capable of writing over memory that it shouldn't betouching. Valgrind, like another other tool, needs to be used intelligentlyas a way of illuminating problems.
Summary
Valgrind is a tool for the x86 and AMD64 architectures and currently runsunder Linux. Valgrind allows the programmer to run the executable inside itsown environment in which it checks for unpaired calls to malloc and other usesofinvalid memory (such as ininitialized memory) or invalid memory operations(such as freeing a block of memory twice or calling the wrong deallocatorfunction). Valgrind does not check use of statically allocated arrays.Related articles
DynamicMemory Allocation, Part 1: Advanced Memory Management
Dynamic Memory Allocation, Part 2: Dynamic Memory Allocation and Virtual Memory
Dynamic Memory Allocation, Part 3: Customized Allocators with Operator New and Operator Delete
Dynamic Memory Allocation, Part 4: Common Memory Management Problems in C++
UnderstandingPointers

Valgrind Mac
Using auto_ptr toavoid memory leaks
This page is part of the debugging series — pages with debugging details for a variety of Ubuntu packages. |
Valgrind is a suite of tools for debugging and profiling programs. There are three tools: a memory error detector, a time profiler, and a space profiler.
For debugging purposes, the memory error detector is a handy tool.
The most important of these is the memory error detector, which tracks the usage of every single bit in a program, and warns if there's something suspicious. Valgrind can detect if memory is used before it has a value, memory is leaked, or memory is used twice.
This makes it ideal for tracking down segmentation faults, bus errors, and general memory leaks.
Please ensure you have packages with debug symbols installed. You can do this by following the instructions at DebuggingProgramCrash.
Make sure Valgrind is installed.
Remove any old Valgrind logs:
Start the program under control of memcheck:
N.B. valgrind can't solve paths, so you should feed it the full program path, to get it: $(which <program>)
- The program will start. It may take a while; this is normal, because Valgrind must perform extensive checking to detect memory errors.
- Perform any actions necessary to reproduce the crash.
Package up the log files (no need if there is only one):
Attach the complete output from Valgrind, contained in valgrind-logs-<program>.tar.gz, in your bug report.
Valgrind Windows
Valgrind FAQ
Online Valgrind
CategoryBugSquadCategoryDebugging
Spanish
Valgrind Windows
Valgrind (last edited 2013-01-03 17:20:38 by brian-murray)



