tags:

views:

534

answers:

3

Can someone provide a quick top level explanation of how valgrind works? ex. How does it know when memory is allocated and freed?

+1  A: 

valgrind sits as a layer between your program and the OS, intercepting calls to the OS requesting memory (de)allocation and recording what is being manipulated before then actually allocating the memory and passing back an equivalent. It's essentially how most code profilers work, except at a much lower level (system calls instead of program function calls).

Amber
+10  A: 

Valgrind basically runs your application in a "sandbox." While running in this sandbox, it is able to insert its own instructions to do advanced debugging and profiling.

From the manual:

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.

So basically, valgrind provides a virtual processor that executes your application. However, before your application instructions are processed, they are passed to tools (such as memcheck). These tools are kind of like plugins, and they are able to modify your application before it is run on the processor.

The great thing about this approach is that you don't have to modify or relink your program at all to run it in valgrind. It does cause your program to run slower, however valgrind isn't meant to measure performance or run during normal execution of your application, so this isn't really an issue.

jheddings
+1  A: 

Valgrind is basically a virtual machine that executes your program. It is a virtual architecture that intercepts each call to allocate/free memory.

Charles Salvia