VALGRIND(1)

๐ŸŒธ NAME ๐ŸŒธ

valgrind โ€” a suite of tools for debugging and profiling programs. Yep bestie, this is the VALGRIND(1) page, with the manual name folded right in near the top like a little name tag. ๐Ÿ’–

โœจ SYNOPSIS โœจ

valgrind [valgrind-options] [your-program] [your-program-options]

๐Ÿ’– DESCRIPTION ๐Ÿ’–

Valgrind is this flexible program for debugging and profiling Linux executables. It's made of a core โ€” which provides a synthetic CPU in software โ€” plus a whole series of debugging and profiling tools. The architecture is modular, so that new tools can be created easily and without disturbing the existing structure. Slay.

Some of the options described below work with all Valgrind tools, and some only work with a few or one. The MEMCHECK OPTIONS section and those below it describe tool-specific options.

This manual page covers only basic usage and options. For more comprehensive information, please see the HTML documentation on your system: $INSTALL/share/doc/valgrind/html/index.html, or online: http://www.valgrind.org/docs/manual/index.html.

๐Ÿ‘‘ TOOL SELECTION OPTIONS ๐Ÿ‘‘

Okay, the single most important option:

  • --tool=<toolname> [default: memcheck] โ€” Run the Valgrind tool called toolname, e.g. memcheck, cachegrind, callgrind, helgrind, drd, massif, dhat, lackey, none, exp-bbv, etc. ๐Ÿ’…

๐ŸŽ€ BASIC OPTIONS ๐ŸŽ€

These options work with all tools.

  • -h, --help โ€” Show help for all options, both for the core and for the selected tool. If the option is repeated it is equivalent to giving --help-debug.
  • --help-debug โ€” Same as --help, but also lists debugging options which usually are only of use to Valgrind's developers.
  • --version โ€” Show the version number of the Valgrind core. Tools can have their own version numbers. There is a scheme in place to ensure that tools only execute when the core version is one they are known to work with. This was done to minimise the chances of strange problems arising from tool-vs-core version incompatibilities.
  • -q, --quiet โ€” Run silently, and only print error messages. Useful if you are running regression tests or have some other automated test machinery.
  • -v, --verbose โ€” Be more verbose. Gives extra information on various aspects of your program, such as: the shared objects loaded, the suppressions used, the progress of the instrumentation and execution engines, and warnings about unusual behaviour. Repeating the option increases the verbosity level.
  • --trace-children=<yes|no> [default: no] โ€” When enabled, Valgrind will trace into sub-processes initiated via the exec system call. This is necessary for multi-process programs.

Note that Valgrind does trace into the child of a fork (it would be difficult not to, since fork makes an identical copy of a process), so this option is arguably badly named. However, most children of fork calls immediately call exec anyway.

  • --trace-children-skip=patt1,patt2,... โ€” This option only has an effect when --trace-children=yes is specified. It allows for some children to be skipped. The option takes a comma separated list of patterns for the names of child executables that Valgrind should not trace into. Patterns may include the metacharacters ? and *, which have the usual meaning.

This can be useful for pruning uninteresting branches from a tree of processes being run on Valgrind. But you should be careful when using it. When Valgrind skips tracing into an executable, it doesn't just skip tracing that executable, it also skips tracing any of that executable's child processes. In other words, the flag doesn't merely cause tracing to stop at the specified executables -- it skips tracing of entire process subtrees rooted at any of the specified executables. ๐Ÿ˜ญ

  • --trace-children-skip-by-arg=patt1,patt2,... โ€” This is the same as --trace-children-skip, with one difference: the decision as to whether to trace into a child process is made by examining the arguments to the child process, rather than the name of its executable.
  • --child-silent-after-fork=<yes|no> [default: no] โ€” When enabled, Valgrind will not show any debugging or logging output for the child process resulting from a fork call. This can make the output less confusing (although more misleading) when dealing with processes that create children. It is particularly useful in conjunction with --trace-children=. Use of this option is also strongly recommended if you are requesting XML output (--xml=yes), since otherwise the XML from child and parent may become mixed up, which usually makes it useless.
  • --vgdb=<no|yes|full> [default: yes] โ€” Valgrind will provide "gdbserver" functionality when --vgdb=yes or --vgdb=full is specified. This allows an external GNU GDB debugger to control and debug your program when it runs on Valgrind. --vgdb=full incurs significant performance overheads, but provides more precise breakpoints and watchpoints. See Debugging your program using Valgrind's gdbserver and GDB for a detailed description.

If the embedded gdbserver is enabled but no gdb is currently being used, the vgdb command line utility can send "monitor commands" to Valgrind from a shell. The Valgrind core provides a set of Valgrind monitor commands. A tool can optionally provide tool specific monitor commands, which are documented in the tool specific chapter.

  • --vgdb-error=<number> [default: 999999999] โ€” Use this option when the Valgrind gdbserver is enabled with --vgdb=yes or --vgdb=full. Tools that report errors will wait for number errors to be reported before freezing the program and waiting for you to connect with GDB. It follows that a value of zero will cause the gdbserver to be started before your program is executed. This is typically used to insert GDB breakpoints before execution, and also works with tools that do not report errors, such as Massif.
  • --vgdb-stop-at=<set> [default: none] โ€” Use this option when the Valgrind gdbserver is enabled with --vgdb=yes or --vgdb=full. The Valgrind gdbserver will be invoked for each error after --vgdb-error have been reported. You can additionally ask the Valgrind gdbserver to be invoked for other events, specified in one of the following ways:
    • a comma separated list of one or more of startup exit abexit valgrindabexit.
    • The values startup exit valgrindabexit respectively indicate to invoke gdbserver before your program is executed, after the last instruction of your program, on Valgrind abnormal exit (e.g. internal error, out of memory, ...).
    • The option abexit is similar to exit but tells to invoke gdbserver only when your application exits abnormally (i.e. with an exit code different of 0).
    • Note: startup and --vgdb-error=0 will both cause Valgrind gdbserver to be invoked before your program is executed. The --vgdb-error=0 will in addition cause your program to stop on all subsequent errors.
    • all to specify the complete set. It is equivalent to --vgdb-stop-at=startup,exit,abexit,valgrindabexit.
    • none for the empty set.
  • --track-fds=<yes|no|all|bad> [default: no] โ€” When enabled, Valgrind will track all file descriptor usage. It will produce errors for bad file descriptor usage like closing a file descriptor twice, using a file descriptor (number) that was never created, or passing an already closed file descriptor to a system call. It will also print out a list of open file descriptors on exit. Or on request, via the gdbserver monitor command v.info open_fds.

When an error is generated, or when listing the still open file descriptors at exit, a stack backtrace of where the file was opened is printed. If the file descriptor has already been closed, it will also include a backtrace of where it was previously closed. Any error will include details relating to the file descriptor such as the file name or socket details.

Use all to also include reporting on stdin, stdout and stderr (or other inherited file descriptors) at exit. If bad option is used, then exclude reporting on leaked file descriptors at exit and only produce errors about bad file decriptors usage.

  • --modify-fds=<no|yes|high> [default: no] โ€” When enabled, when the program opens a new file descriptor, the highest available file descriptor is returned instead of the lowest one. Use yes to restrict the feature from the 0/1/2 file descriptors as they're often used for stdout/stderr redirection.
  • --time-stamp=<yes|no> [default: no] โ€” When enabled, each message is preceded with an indication of the elapsed wallclock time since startup, expressed as days, hours, minutes, seconds and milliseconds.
  • --log-fd=<number> [default: 2, stderr] โ€” Specifies that Valgrind should send all of its messages to the specified file descriptor. The default, 2, is the standard error channel (stderr). Note that this may interfere with the client's own use of stderr, as Valgrind's output will be interleaved with any output that the client sends to stderr.
  • --log-file=<filename> โ€” Specifies that Valgrind should send all of its messages to the specified file. If the file name is empty, it causes an abort. There are three special format specifiers that can be used in the file name.
    • %p is replaced with the current process ID. This is very useful for programs that invoke multiple processes. WARNING: If you use --trace-children=yes and your program invokes multiple processes OR your program forks without calling exec afterwards, and you don't use this specifier (or the %q specifier below), the Valgrind output from all those processes will go into one file, possibly jumbled up, and possibly incomplete. Note: If the program forks and calls exec afterwards, Valgrind output of the child from the period between fork and exec will be lost. Fortunately this gap is really tiny for most programs; and modern programs use posix_spawn anyway.
    • %n is replaced with a file sequence number unique for this process. This is useful for processes that produces several files from the same filename template. ๐Ÿ“
  • %q{FOO} โ€” gets swapped out for whatever's in the environment variable FOO. If the {FOO} bit is malformed ๐Ÿซ  it causes an abort. Honestly this specifier is rarely needed, but it's so useful in certain circumstances (eg. when running MPI programs). The whole idea: you name a variable that'll be set differently for each process in the job โ€” like BPROC_RANK, or whatever is applicable in your MPI setup. And if the named environment variable is not set, that also causes an abort. Heads up: in some shells the { and } characters may need to be escaped with a backslash.
  • %% โ€” gets replaced with a literal %.
If a % is followed by any other character, it causes an abort. That's it. No vibe check, just abort ๐Ÿ’€

If the file name specifies a relative file name, it gets put in the program's initial working directory โ€” that's the current directory when the program started its execution after the fork or after the exec. If it specifies an absolute file name (ie. starts with /) then it's put there. Easy โœจ

  • --log-socket=<ip-address:port-number> โ€” tells Valgrind to send, like, all of its messages to the specified port at the specified IP address ๐Ÿ“จ. The port may be omitted, in which case port 1500 is used. If a connection can't be made to the specified socket, Valgrind falls back to writing output to the standard error (stderr) โ€” no drama, it just goes home. This option is intended to be used together with the valgrind-listener program. For further details, see the commentary in the manual ๐Ÿ‘‘
  • --enable-debuginfod=<no|yes> [default: yes] โ€” when enabled, Valgrind will attempt to download missing debuginfo from debuginfod servers if space-separated server URLs are present in the $DEBUGINFOD_URLS environment variable. This option is supported on Linux only ๐Ÿง (sorry bestie).

These options are used by all tools that can report errors โ€” think Memcheck โ€” but not Cachegrind ๐Ÿšซ.

  • --xml=<yes|no> [default: no] โ€” when enabled, the important parts of the output (e.g. tool error messages) will be in XML format rather than plain text. And not just that: the XML output gets sent to a different output channel than the plain text output. So you also must use one of --xml-fd, --xml-file or --xml-socket to specify where the XML is to be sent โ€” otherwise where's it even going, bestie? ๐Ÿ˜ญ

Less important messages will still be printed in plain text, but since the XML output and plain text output are sent to different output channels (the destination of the plain text output is still controlled by --log-fd, --log-file and --log-socket) this should not cause problems.

This option is aimed at making life easier for tools that consume Valgrind's output as input, such as GUI front ends. Currently this option works with Memcheck, Helgrind and DRD. The output format is specified in the file docs/internals/xml-output-protocol4.txt in the source tree for Valgrind 3.5.0 or later ๐Ÿ“„.

The recommended options for a GUI to pass, when requesting XML output, are: --xml=yes to enable XML output, --xml-file to send the XML output to a (presumably GUI-selected) file, --log-file to send the plain text output to a second GUI-selected file, --child-silent-after-fork=yes, and -q to restrict the plain text output to critical error messages created by Valgrind itself. For example, failure to read a specified suppressions file counts as a critical error message. In this way, for a successful run the text output file will be empty ๐ŸŽ‰. But if it isn't empty, then it'll contain important information which the GUI user should be made aware of.

  • --xml-fd=<number> [default: -1, disabled] โ€” says Valgrind should send its XML output to the specified file descriptor. It must be used in conjunction with --xml=yes ๐Ÿซถ
  • --xml-file=<filename> โ€” says Valgrind should send its XML output to the specified file. It must be used in conjunction with --xml=yes. Any %p or %q sequences appearing in the filename are expanded in exactly the same way as they are for --log-file. See the description of --log-file for details ๐Ÿ‘€
  • --xml-socket=<ip-address:port-number> โ€” says Valgrind should send its XML output the specified port at the specified IP address. It must be used in conjunction with --xml=yes. The form of the argument is the same as that used by --log-socket. See the description of --log-socket for further details ๐Ÿ’…
  • --xml-user-comment=<string> โ€” embeds an extra user comment string at the start of the XML output โœ๏ธ. Only works when --xml=yes is specified; otherwise it's just ignored, rip.
  • --demangle=<yes|no> [default: yes] โ€” enable/disable automatic demangling (decoding) of C++, D, Rust, Java, Ada names. Enabled by default. When enabled, Valgrind will attempt to translate encoded names in the listed languages back to something approaching the original ๐Ÿฆ‹. Note that the callgrind tool always disables Ada demangling in order to differentiate overloaded functions and procedures in the callgraph. The demangler handles symbols mangled by g++ versions 2.X, 3.X and 4.X.

An important fact about demangling: function names mentioned in suppressions files should be in their mangled form. Valgrind does not demangle function names when searching for applicable suppressions, because to do otherwise would make suppression file contents dependent on the state of Valgrind's demangling machinery, and also slow down suppression matching. So keep 'em mangled, okay? ๐Ÿ™

  • --num-callers=<number> [default: 12] โ€” specifies the maximum number of entries shown in stack traces that identify program locations. Note that errors are commoned up using only the top four function locations (the place in the current function, and that of its three immediate callers). So this doesn't affect the total number of errors reported, just how much stack you see ๐ŸŒธ

The maximum value for this is 500. Higher settings will make Valgrind run a bit more slowly and take a bit more memory, but can be useful when working with programs with deeply-nested call chains ๐ŸŒ€

The minimum value for this is 2. A value of 1 is not allowed, for two reasons. Firstly, some of the default suppressions use "..." which is forbidden with --num-callers=1. Secondly, it would make leak suppressions match all allocations using the allocation function (e.g., malloc). So likeโ€ฆ no. ๐Ÿšซ

  • --unw-stack-scan-thresh=<number> [default: 0] , --unw-stack-scan-frames=<number> [default: 5] โ€” stack-scanning support is available only on ARM targets ๐Ÿฆพ

These flags enable and control stack unwinding by stack scanning. When the normal stack unwinding mechanisms โ€” usage of Dwarf CFI records, and frame-pointer following โ€” fail, stack scanning may be able to recover a stack trace.

Note that stack scanning is an imprecise, heuristic mechanism that may give very misleading results, or none at all ๐Ÿ˜ฌ. It should be used only in emergencies, when normal unwinding fails, and it is important to nevertheless have stack traces.

Stack scanning is a simple technique: the unwinder reads words from the stack, and tries to guess which of them might be return addresses, by checking to see if they point just after ARM or Thumb call instructions. If so, the word is added to the backtrace ๐ŸŽฏ

The main danger occurs when a function call returns, leaving its return address exposed, and a new function is called, but the new function does not overwrite the old address. The result of this is that the backtrace may contain entries for functions which have already returned, and so be very confusing ๐Ÿ’€

A second limitation of this implementation is that it will scan only the page (4KB, normally) containing the starting stack pointer. If the stack frames are large, this may result in only a few (or not even any) being present in the trace. Also, if you are unlucky and have an initial stack pointer near the end of its containing page, the scan may miss all interesting frames ๐Ÿ™ˆ

By default stack scanning is disabled. The normal use case is to ask for it when a stack trace would otherwise be very short. So, to enable it, use --unw-stack-scan-thresh=number. This requests Valgrind to try using stack scanning to "extend" stack traces which contain fewer than number frames.

If stack scanning does take place, it will only generate at most the number of frames specified by --unw-stack-scan-frames. Typically, stack scanning generates so many garbage entries that this value is set to a low value (5) by default. In no case will a stack trace larger than the value specified by --num-callers be created ๐Ÿ‘‘

  • --error-limit=<yes|no> [default: yes] โ€” when enabled, Valgrind stops reporting errors after 10,000,000 in total, or 1,000 different ones, have been seen. This is to stop the error tracking machinery from becoming a huge performance overhead in programs with many errors ๐Ÿƒโ€โ™€๏ธ๐Ÿ’จ
  • --error-exitcode=<number> [default: 0] โ€” specifies an alternative exit code to return if Valgrind reported any errors in the run. When set to the default value (zero), the return value from Valgrind will always be the return value of the process being simulated. When set to a nonzero value, that value is returned instead, if Valgrind detects any errors ๐Ÿšจ. This is super useful for using Valgrind as part of an automated test suite, since it makes it easy to detect test cases for which Valgrind has reported errors, just by inspecting return codes. When set to a nonzero value and Valgrind detects no error, the return value of Valgrind will be the return value of the program being simulated โœจ
  • --exit-on-first-error=<yes|no> [default: no] โ€” if this option is enabled, Valgrind exits on the first error ๐Ÿ›‘. A nonzero exit value must be defined using the --error-exitcode option. Useful if you're running regression tests or have some other automated test machinery.
  • --error-markers=<begin>,<end> [default: none] โ€” when errors are output as plain text (i.e. XML not used), --error-markers instructs to output a line containing the begin (end) string before (after) each error ๐Ÿท๏ธ

Such marker lines facilitate searching for errors and/or extracting errors in an output file that contain valgrind errors mixed with the program output.

Note that empty markers are accepted. So, only using a begin (or an end) marker is possible ๐ŸŽ€

  • --show-error-list=no|yes|all [default: no] โ€” okay so if this one is yes, then for tools that report errors, valgrind will show the list of detected errors and the list of used suppressions at exit. โœจ The value all means it also shows the list of suppressed errors.

Heads up, bestie: at verbosity 2 and above, valgrind automatically shows the list of detected errors and the list of used suppressions at exit, unless --show-error-list=no is selected.

  • -s โ€” specifying -s is literally equivalent to --show-error-list=yes. ๐Ÿ’…
  • --sigill-diagnostics=<yes|no> [default: yes] โ€” turns printing of illegal instruction diagnostics on/off. Itโ€™s enabled by default, but defaults to disabled when --quiet is given. The default can always be explicitly overridden by giving this option. ๐Ÿซถ

When enabled, a warning message gets printed, along with some diagnostics, whenever an instruction is encountered that Valgrind cannot decode or translate, before the program is given a SIGILL signal. Often an illegal instruction indicates a bug in the program or missing support for the particular instruction in Valgrind. But some programs deliberately try to execute an instruction that might be missing and trap the SIGILL signal to detect processor features. Using this flag makes it possible to avoid the diagnostic output that you would otherwise get in such cases. ๐Ÿ˜ญ

  • --keep-debuginfo=<yes|no> [default: no] โ€” when enabled, keep (โ€œarchiveโ€) symbols and all other debuginfo for unloaded code. This allows saved stack traces to include file/line info for code that has been dlclose'd (or similar). Be careful with this, since it can lead to unbounded memory use for programs which repeatedly load and unload shared objects. ๐Ÿ’€

Some tools and some functionalities have only limited support for archived debug info. Memcheck fully supports it. Generally, tools that report errors can use archived debug info to show the error stack traces. The known limitations are: Helgrind's past access stack trace of a race condition does not use archived debug info. Massif (and more generally the xtree Massif output format) does not make use of archived debug info. Only Memcheck has been (somewhat) tested with --keep-debuginfo=yes, so other tools may have unknown limitations. ๐Ÿฆ‹

  • --show-below-main=<yes|no> [default: no] โ€” by default, stack traces for errors do not show any functions that appear beneath main because most of the time itโ€™s uninteresting C library stuff and/or gobbledygook. Alternatively, if main is not present in the stack trace, stack traces will not show any functions below main-like functions such as glibcโ€™s __libc_start_main. Furthermore, if main-like functions are present in the trace, they are normalised as (below main), in order to make the output more deterministic. ๐ŸŽ€

If this option is enabled, all stack trace entries will be shown and main-like functions will not be normalised. โœจ

  • --fullpath-after=<string> [default: don't show source paths] โ€” by default Valgrind only shows the filenames in stack traces, but not full paths to source files. When using Valgrind in large projects where the sources reside in multiple different directories, this can be inconvenient. --fullpath-after provides a flexible solution to this problem. When this option is present, the path to each source file is shown, with the following all-important caveat: if string is found in the path, then the path up to and including string is omitted, else the path is shown unmodified. Note that string is not required to be a prefix of the path. ๐Ÿ’–

For example, consider a file named /home/janedoe/blah/src/foo/bar/xyzzy.c. Specifying --fullpath-after=/home/janedoe/blah/src/ will cause Valgrind to show the name as foo/bar/xyzzy.c.

Because the string is not required to be a prefix, --fullpath-after=src/ will produce the same output. This is useful when the path contains arbitrary machine-generated characters. For example, the path /my/build/dir/C32A1B47/blah/src/foo/xyzzy can be pruned to foo/xyzzy using --fullpath-after=/blah/src/. ๐ŸŒธ

If you simply want to see the full path, just specify an empty string: --fullpath-after= โ€” that isnโ€™t a special case, merely a logical consequence of the above rules.

Finally, you can use --fullpath-after multiple times. Any appearance of it causes Valgrind to switch to producing full paths and applying the above filtering rule. Each produced path is compared against all the --fullpath-after-specified strings, in the order specified. The first string to match causes the path to be truncated as described above. If none match, the full path is shown. This facilitates chopping off prefixes when the sources are drawn from a number of unrelated directories. ๐Ÿงš

  • --extra-debuginfo-path=<path> [default: undefined and unused] โ€” by default Valgrind searches in several well-known paths for debug objects, such as /usr/lib/debug/. ๐Ÿ‘‘

However, there may be scenarios where you may wish to put debug objects at an arbitrary location, such as external storage when running Valgrind on a mobile device with limited local storage. Another example might be a situation where you do not have permission to install debug object packages on the system where you are running Valgrind.

In these scenarios, you may provide an absolute path as an extra, final place for Valgrind to search for debug objects by specifying --extra-debuginfo-path=/path/to/debug/objects. The given path will be prepended to the absolute path name of the searched-for object. For example, if Valgrind is looking for the debuginfo for /w/x/y/zz.so and --extra-debuginfo-path=/a/b/c is specified, it will look for a debug object at /a/b/c/w/x/y/zz.so. ๐Ÿ”ฅ

This flag should only be specified once. If it is specified multiple times, only the last instance is honoured. ๐Ÿ’…

  • --debuginfo-server=ipaddr:port [default: undefined and unused] โ€” this is a new, experimental, feature introduced in version 3.9.0. ๐Ÿฆ‹

In some scenarios it may be convenient to read debuginfo from objects stored on a different machine. With this flag, Valgrind will query a debuginfo server running on ipaddr and listening on port, if it cannot find the debuginfo object in the local filesystem.

The debuginfo server must accept TCP connections on port port. The debuginfo server is contained in the source file auxprogs/valgrind-di-server.c. It will only serve from the directory it is started in. port defaults to 1500 in both client and server if not specified. โœจ

If Valgrind looks for the debuginfo for /w/x/y/zz.so by using the debuginfo server, it will strip the pathname components and merely request zz.so on the server. That in turn will look only in its current working directory for a matching debuginfo object.

The debuginfo data is transmitted in small fragments (8 KB) as requested by Valgrind. Each block is compressed using LZO to reduce transmission time. The implementation has been tuned for best performance over a single-stage 802.11g (WiFi) network link. ๐ŸŒˆ

Note that checks for matching primary vs debug objects, using GNU debuglink CRC scheme, are performed even when using the debuginfo server. To disable such checking, you need to also specify --allow-mismatched-debuginfo=yes. ๐Ÿ˜ญ

By default the Valgrind build system will build valgrind-di-server for the target platform, which is almost certainly not what you want. So far we have been unable to find out how to get automake/autoconf to build it for the build platform. If you want to use it, you will have to recompile it by hand using the command shown at the top of auxprogs/valgrind-di-server.c. ๐Ÿ’€

Valgrind can also download debuginfo via debuginfod. See the DEBUGINFOD section for more information. ๐ŸŽ€

  • --allow-mismatched-debuginfo=no|yes [no] โ€” when reading debuginfo from separate debuginfo objects, Valgrind will by default check that the main and debuginfo objects match, using the GNU debuglink mechanism. This guarantees that it does not read debuginfo from out of date debuginfo objects, and also ensures that Valgrind canโ€™t crash as a result of mismatches. ๐Ÿซถ

This check can be overridden using --allow-mismatched-debuginfo=yes. This may be useful when the debuginfo and main objects have not been split in the proper way. Be careful when using this, though: it disables all consistency checking, and Valgrind has been observed to crash when the main and debuginfo objects donโ€™t match. ๐Ÿ˜ญ

  • --suppressions=<filename> [default: $PREFIX/lib/valgrind/default.supp] โ€” specifies an extra file from which to read descriptions of errors to suppress. You may use up to 100 extra suppression files. ๐Ÿ’–
  • --gen-suppressions=<yes|no|all> [default: no] โ€” when set to yes, Valgrind will pause after every error shown and print the line:
---- Print suppression ? --- [Return/N/n/Y/y/C/c] ----

Pressing Ret, or N Ret or n Ret, causes Valgrind to continue execution without printing a suppression for this error. โœจ

Pressing Y Ret or y Ret causes Valgrind to write a suppression for this error. You can then cut and paste it into a suppression file if you donโ€™t want to hear about the error in the future. ๐Ÿ’…

When set to all, Valgrind will print a suppression for every reported error, without querying the user. ๐Ÿ”ฅ

This option is particularly useful with C++ programs, as it prints out the suppressions with mangled names, as required. ๐Ÿงš

Note that the suppressions printed are as specific as possible. You may want to common up similar ones, by adding wildcards to function names, and by using frame-level wildcards. The wildcarding facilities are powerful yet flexible, and with a bit of careful editing, you may be able to suppress a whole family of related errors with only a few suppressions. ๐ŸŒธ

Sometimes two different errors are suppressed by the same suppression, in which case Valgrind will output the suppression more than once, but you only need to have one copy in your suppression file (but having more than one wonโ€™t cause problems). Also, the suppression name is given as <insert a suppression name here>; the name doesnโ€™t really matter, itโ€™s only used with the -v option which prints out all used suppression records. ๐Ÿ‘‘

  • --input-fd=<number> [default: 0, stdin] โ€” okay so when you're using --gen-suppressions=yes, Valgrind literally stops and waits for you to type at it every time an error pops up. By default it reads that from stdin, which is a whole mess if your program closes stdin (rude, honestly). This option lets you point it at a different file descriptor to read your input from instead. ๐Ÿ’…
  • --dsymutil=no|yes [yes] โ€” macOS girlies only, this one's for you ๐ŸŽ. So macOS does this deferred debuginfo linking thing: when object files with debuginfo get linked into a .dylib or an executable, the debuginfo does not get copied into the final file. Nope. Instead it has to be linked manually by running dsymutil โ€” a system-provided utility โ€” on the executable or .dylib. The resulting combined debuginfo goes in a directory alongside the executable or .dylib, except with the extension .dSYM.
    • With --dsymutil=no, Valgrind detects cases where the .dSYM directory is either missing, or is there but doesn't look like it matches the associated executable or .dylib โ€” most likely because it's out of date. In those cases, Valgrind prints a warning message but takes no further action.
    • With --dsymutil=yes, Valgrind will, in such cases, automatically run dsymutil as necessary to bring the debuginfo up to date. For all practical purposes, if you always use --dsymutil=yes, there's never any need to run dsymutil manually or as part of your application's build system, since Valgrind will run it as necessary. Iconic behaviour, honestly. โœจ

Valgrind will not attempt to run dsymutil on any executable or library in /usr/, /bin/, /sbin/, /opt/, /sw/, /System/, /Library/ or /Applications/, since dsymutil will always fail in such situations. It fails both because the debuginfo for such pre-installed system components isn't available anywhere, and also because it would require write privileges in those directories. ๐Ÿ™ˆ

โš ๏ธ Be careful with --dsymutil=yes, bestie โ€” it will cause pre-existing .dSYM directories to be silently deleted and re-created. Also, dsymutil is quite slow, sometimes excessively so. Like, excessively. ๐Ÿ˜ญ
  • --max-stackframe=<number> [default: 2000000] โ€” this is the maximum size of a stack frame. If the stack pointer moves by more than this amount, Valgrind assumes your program is switching to a different stack.

You may need this option if your program has large stack-allocated arrays. Valgrind keeps track of your program's stack pointer, and if it changes by more than the threshold amount, Valgrind assumes your program is switching to a different stack, and Memcheck behaves differently than it would for a stack pointer change smaller than the threshold. Usually this heuristic works well. However, if your program allocates large structures on the stack, this heuristic gets fooled, and Memcheck will subsequently report large numbers of invalid stack accesses. This option lets you change the threshold to a different value.

You should only consider using this option if Valgrind's debug output directs you to do so โ€” in that case it'll tell you the new threshold you should specify. ๐Ÿซถ

In general, allocating large structures on the stack is a bad idea, because you can easily run out of stack space (especially on systems with limited memory, or which expect to support large numbers of threads each with a small stack), and also because the error checking performed by Memcheck is more effective for heap-allocated data than for stack-allocated data. If you have to use this option, you may wish to consider rewriting your code to allocate on the heap rather than on the stack. Glow-up your code, basically. โœจ

  • --main-stacksize=<number> [default: use current 'ulimit' value] โ€” specifies the size of the main thread's stack.

To simplify its memory management, Valgrind reserves all required space for the main thread's stack at startup. Which means it needs to know the required stack size at startup.

By default, Valgrind uses the current "ulimit" value for the stack size, or 16 MB, whichever is lower. In many cases this gives a stack size in the range 8 to 16 MB, which almost never overflows for most applications. Slay.

If you need a larger total stack size, use --main-stacksize to specify it. Only set it as high as you actually need, since reserving far more space than you need (like, hundreds of megabytes more than you need) constrains Valgrind's memory allocators and may reduce the total amount of memory that Valgrind can use. This is only really significant on 32-bit machines, ngl.

On Linux, you may request a stack of size up to 2GB. Valgrind will stop with a diagnostic message if the stack cannot be allocated. ๐Ÿ’€

--main-stacksize only affects the stack size for the program's initial thread. It has no bearing on the size of thread stacks, as Valgrind doesn't allocate those.

You may need to use both --main-stacksize and --max-stackframe together. It's important to understand that --main-stacksize sets the maximum total stack size, whilst --max-stackframe specifies the largest size of any one stack frame. You'll have to work out the --main-stacksize value for yourself (usually if your application segfaults). But Valgrind will tell you the needed --max-stackframe size, if necessary. Bestie's got your back. ๐Ÿซถ

As discussed further in the description of --max-stackframe, needing a large stack is a sign of potential portability problems. Your best bet is to place all large data in heap-allocated memory.

  • --max-threads=<number> [default: 500] โ€” by default, Valgrind can handle up to 500 threads. Occasionally that number is too small. Use this option to set a different limit. E.g. --max-threads=3000. ๐Ÿงต
  • --max-guard-pages=<number> [default: 500] โ€” by default, Valgrind can handle up to 500 madvise guard pages. With thread-heavy workloads the default value might not be sufficient. Use this option to set a different limit. E.g. --max-guard-pages=3000. If --max-guard-pages isn't set explicitly, then it'll default to the --max-threads setting.
  • --realloc-zero-bytes-frees=yes|no [default: yes for glibc no otherwise] โ€” okay so the behaviour of realloc() with a size of zero is implementation defined in C17 and undefined in C23. Valgrind tries to work the same way as the underlying system and C runtime library that it was configured and built on. However, if you use a different C runtime library, then this default may be wrong. ๐Ÿ‘€ If the value is yes, then realloc will deallocate the memory and return NULL. If the value is no, then realloc will not deallocate the memory and the size will be handled as though it were one byte.

As an example, if you use Valgrind installed via a package on a Linux distro using GNU libc but link your test executable with musl libc or the JEMalloc library, then consider using --realloc-zero-bytes-frees=no.

Address Sanitizer has a similar and even wordier option: allocator_frees_and_returns_null_on_realloc_zero. Not us being out-wordied by ASan ๐Ÿ˜ญ๐Ÿ’€

Okay so if your tool has its own little malloc situation going on โ€” hi Memcheck, Massif, Helgrind, DRD ๐Ÿ’… โ€” these options are absolutely for you.

  • --alignment=<number> [default: 8 or 16, depending on the platform] โ€” By default, Valgrind's malloc, realloc, etc., return a block whose starting address is 8-byte aligned or 16-byte aligned (the value depends on the platform and matches the platform default). This option lets you specify a different alignment. The supplied value must be greater than or equal to the default, less than or equal to 4096, and must be a power of two. No cap, but also literally a cap: 4096, bestie.
  • --redzone-size=<number> [default: depends on the tool] โ€” Valgrind's malloc, realloc, etc., add padding blocks before and after each heap block allocated by the program being run. Such padding blocks are called redzones. The default value for the redzone size depends on the tool. For example, Memcheck adds and protects a minimum of 16 bytes before and after each block allocated by the client. This lets it detect block underruns or overruns of up to 16 bytes.

Increasing the redzone size makes it possible to detect overruns of larger distances, but increases the amount of memory used by Valgrind. Decreasing the redzone size will reduce the memory needed by Valgrind but also reduces the chances of detecting over/underruns, so it is not recommended. Do not do the tiny-redzone speedrun, bestie.

  • --xtree-memory=none|allocs|full [default: none] โ€” Tools replacing Valgrind's malloc, realloc, etc., can optionally produce an execution tree detailing which piece of code is responsible for heap memory usage. See Execution Trees for a detailed explanation about execution trees.
    • When set to none, no memory execution tree is produced.
    • When set to allocs, the memory execution tree gives the current number of allocated bytes and the current number of allocated blocks.
    • When set to full, the memory execution tree gives 6 different measurements: the current number of allocated bytes and blocks (same values as for allocs), the total number of allocated bytes and blocks, the total number of freed bytes and blocks.

Note that the overhead in cpu and memory to produce an xtree depends on the tool. The overhead in cpu is small for the value allocs, as the information needed to produce this report is maintained in any case by the tool. For massif and helgrind, specifying full implies to capture a stack trace for each free operation, while normally these tools only capture an allocation stack trace. For Memcheck, the cpu overhead for the value full is small, as this can only be used in combination with --keep-stacktraces=alloc-and-free or --keep-stacktraces=alloc-then-free, which already records a stack trace for each free operation. The memory overhead varies between 5 and 10 words per unique stacktrace in the xtree, plus the memory needed to record the stack trace for the free operations, if needed specifically for the xtree. It's giving detailed but expensive, iykyk.

  • --xtree-memory-file=<filename> [default: xtmemory.kcg.%p] โ€” Specifies that Valgrind should produce the xtree memory report in the specified file. Any %p or %q sequences appearing in the filename are expanded in exactly the same way as they are for --log-file. See the description of --log-file for details.

If the filename contains the extension .ms, then the produced file format will be a massif output file format. If the filename contains the extension .kcg or no extension is provided or recognised, then the produced file format will be a callgrind output format.

See Execution Trees for a detailed explanation about execution trees formats. file name lore โœจ


๐ŸŒˆ UNCOMMON OPTIONS ๐ŸŒˆ

These options apply to all tools, as they affect certain obscure workings of the Valgrind core. Most people won't need to use them. Lowkey deep lore territory, but we're going there together. ๐Ÿซถ

  • --smc-check=<none|stack|all|all-non-file> [default: all-non-file for x86/amd64/s390x, stack for other archs] โ€” This option controls Valgrind's detection of self-modifying code. If no checking is done, when a program executes some code, then overwrites it with new code, and executes the new code, Valgrind will continue to execute the translations it made for the old code. This will likely lead to incorrect behaviour and/or crashes. Like, actual crash city. Do not ignore this one.

For "modern" architectures โ€” anything that's not x86, amd64 or s390x โ€” the default is stack. This is because a correct program must take explicit action to reestablish D-I cache coherence following code modification. Valgrind observes and honours such actions, with the result that self-modifying code is transparently handled with zero extra cost.

For x86, amd64 and s390x, the program is not required to notify the hardware of required D-I coherence syncing. Hence the default is all-non-file, which covers the normal case of generating code into an anonymous (non-file-backed) mmap'd area.

The meanings of the four available settings are as follows. No detection (none), detect self-modifying code on the stack (which is used by GCC to implement nested functions) (stack), detect self-modifying code everywhere (all), and detect self-modifying code everywhere except in file-backed mappings (all-non-file).

Running with all will slow Valgrind down noticeably. Running with none will rarely speed things up, since very little code gets dynamically generated in most programs. The VALGRIND_DISCARD_TRANSLATIONS client request is an alternative to --smc-check=all and --smc-check=all-non-file that requires more programmer effort but allows Valgrind to run your program faster, by telling it precisely when translations need to be re-made.

--smc-check=all-non-file provides a cheaper but more limited version of --smc-check=all. It adds checks to any translations that do not originate from file-backed memory mappings. Typical applications that generate code, for example JITs in web browsers, generate code into anonymous mmaped areas, whereas the "fixed" code of the browser always lives in file-backed mappings. --smc-check=all-non-file takes advantage of this observation, limiting the overhead of checking to code which is likely to be JIT generated. Smart, honestly.

  • --read-inline-info=<yes|no> [default: see below] โ€” When enabled, Valgrind will read information about inlined function calls from DWARF3 debug info. This slows Valgrind startup and makes it use more memory (typically for each inlined piece of code, 6 words and space for the function name), but it results in more descriptive stacktraces. Currently, this functionality is enabled by default only for Linux, FreeBSD, Android and Solaris targets and only for the tools Memcheck, Massif, Helgrind and DRD. Here is an example of some stacktraces with --read-inline-info=no:
==15380== Conditional jump or move depends on uninitialised value(s)
==15380==    at 0x80484EA: main (inlinfo.c:6)
==15380==
==15380== Conditional jump or move depends on uninitialised value(s)
==15380==    at 0x8048550: fun_noninline (inlinfo.c:6)
==15380==    by 0x804850E: main (inlinfo.c:34)
==15380==
==15380== Conditional jump or move depends on uninitialised value(s)
==15380==    at 0x8048520: main (inlinfo.c:6)

And here are the same errors with --read-inline-info=yes:

==15377== Conditional jump or move depends on uninitialised value(s)
==15377==    at 0x80484EA: fun_d (inlinfo.c:6)
==15377==    by 0x80484EA: fun_c (inlinfo.c:14)
==15377==    by 0x80484EA: fun_b (inlinfo.c:20)
==15377==    by 0x80484EA: fun_a (inlinfo.c:26)
==15377==    by 0x80484EA: main (inlinfo.c:33)
==15377==
==15377== Conditional jump or move depends on uninitialised value(s)
==15377==    at 0x8048550: fun_d (inlinfo.c:6)
==15377==    by 0x8048550: fun_noninline (inlinfo.c:41)
==15377==    by 0x804850E: main (inlinfo.c:34)
==15377==
==15377== Conditional jump or move depends on uninitialised value(s)
==15377==    at 0x8048520: fun_d (inlinfo.c:6)
==15377==    by 0x8048520: main (inlinfo.c:35)
  • --read-var-info=<yes|no> [default: no] โ€” When enabled, Valgrind will read information about variable types and locations from DWARF3 debug info. This slows Valgrind startup significantly and makes it use significantly more memory, but for the tools that can take advantage of it (Memcheck, Helgrind, DRD) it can result in more precise error messages. For example, here are some standard errors issued by Memcheck:
==15363== Uninitialised byte(s) found during client check request
==15363==    at 0x80484A9: croak (varinfo1.c:28)
==15363==    by 0x8048544: main (varinfo1.c:55)
==15363==  Address 0x80497f7 is 7 bytes inside data symbol "global_i2"
==15363==
==15363== Uninitialised byte(s) found during client check request
==15363==    at 0x80484A9: croak (varinfo1.c:28)
==15363==    by 0x8048550: main (varinfo1.c:56)
==15363==  Address 0xbea0d0cc is on thread 1's stack
==15363==  in frame #1, created by main (varinfo1.c:45)

And here are the same errors with --read-var-info=yes:

==15370== Uninitialised byte(s) found during client check request
==15370==    at 0x80484A9: croak (varinfo1.c:28)
==15370==    by 0x8048544: main (varinfo1.c:55)
==15370==  Location 0x80497f7 is 0 bytes inside global_i2[7],
==15370==  a global variable declared at varinfo1.c:41
==15370==
==15370== Uninitialised byte(s) found during client check request
==15370==    at 0x80484A9: croak (varinfo1.c:28)
==15370==    by 0x8048550: main (varinfo1.c:56)
==15370==  Location 0xbeb4a0cc is 0 bytes inside local var "local"
==15370==  declared at varinfo1.c:46, in frame #1 of thread 1
  • --vgdb-poll=<number> [default: 5000] โ€” As part of its main loop, the Valgrind scheduler will poll to check if some activity (such as an external command or some input from a gdb) has to be handled by gdbserver. This activity poll will be done after having run the given number of basic blocks (or slightly more than the given number of basic blocks). This poll is quite cheap so the default value is set relatively low. You might further decrease this value if vgdb cannot use ptrace system call to interrupt Valgrind if all threads are (most of the time) blocked in a system call. Poll girlie pops in, checks the vibes, dips out. ๐Ÿฆ‹
  • --vgdb-shadow-registers=no|yes [default: no] โ€” okay so when you flip this on, gdbserver literally exposes the Valgrind shadow registers to GDB ๐Ÿ‘€ which means you can peek at them and even mess with their values straight from GDB. It's giving backstage access ๐Ÿ’… ngl the one catch is it only works with GDB version 7.1 or later โ€” older GDBs just aren't invited to the party.
  • --vgdb-prefix=<prefix> [default: /tmp/vgdb-pipe] โ€” bestie, for gdb/vgdb to actually talk to each other, the Valgrind gdbserver has to create 3 files: two named FIFOs plus an mmap shared memory file ๐ŸŽ€. This option is literally just you choosing the directory and the prefix for where those three little guys get born. That's it, that's the whole vibe.

๐Ÿงš the libc-freeres saga

  • --run-libc-freeres=<yes|no> [default: yes] โ€” heads up, this one only matters if you're running Valgrind on Linux with GNU libc ๐Ÿ’œ.

So here's the lore: the GNU C library (libc.so), which literally every program uses, may allocate memory for its own personal use. And usually it does not bother freeing that memory when the program ends โ€” and honestly? iconic of it, because there'd be no point, the Linux kernel reclaims all process resources when a process exits anyway, so freeing would just be slowing things down for no reason ๐Ÿ˜Œ.

The glibc authors clocked that this behaviour makes leak checkers like Valgrind falsely report leaks in glibc when a leak check happens at exit ๐Ÿ˜ญ. So to avoid that whole mess, they provided a routine called __libc_freeres specifically to make glibc release all the memory it has allocated. Memcheck therefore tries to run __libc_freeres at exit ๐Ÿซถ.

BUT โ€” and this is the part where it gets messy โ€” in some very old versions of glibc, __libc_freeres is buggy enough to cause segmentation faults ๐Ÿ’€. This was particularly noticeable on Red Hat 7.1. So this option exists purely to inhibit the run of __libc_freeres. If your program seems to run fine on Valgrind but segfaults at exit, --run-libc-freeres=no might fix that for you โ€” although at the cost of possibly falsely reporting space leaks in libc.so ๐ŸŽ€.

  • --run-cxx-freeres=<yes|no> [default: yes] โ€” the C++ remix of the above โœจ only relevant when running Valgrind on Linux, FreeBSD or Solaris C++ programs using libstdc++.

Same energy, different library: the GNU Standard C++ library (libstdc++.so), which all C++ programs compiled with g++ use, may allocate memory for its own uses. Usually it doesn't bother to free that memory when the program ends โ€” no point, the kernel reclaims all process resources when a process exits anyway, so it would just slow things down ๐Ÿ’….

The gcc authors realised this behaviour causes leak checkers like Valgrind to falsely report leaks in libstdc++ when a leak check is done at exit. So to dodge that, they provided a routine called __gnu_cxx::__freeres specifically to make libstdc++ release all memory it has allocated. Memcheck therefore tries to run __gnu_cxx::__freeres at exit ๐ŸŒธ.

And for the sake of flexibility and unforeseen problems with __gnu_cxx::__freeres, the option --run-cxx-freeres=no exists โ€” although at the cost of possibly falsely reporting space leaks in libstdc++.so ๐Ÿ˜ญ.


  • --sim-hints=hint1,hint2,... โ€” this one passes miscellaneous hints to Valgrind that slightly modify the simulated behaviour in nonstandard or dangerous ways, possibly to help simulation of strange features ๐Ÿšจ. By default no hints are enabled. Use with caution! Currently known hints are:
    • lax-ioctls: be very lax about ioctl handling โ€” the only assumption is that the size is correct. Doesn't require the full buffer to be initialised when writing. Without this, using some device drivers with a large number of strange ioctl commands becomes very tiresome ๐Ÿ˜ฎโ€๐Ÿ’จ.
    • fuse-compatible: enables special handling for certain system calls that may block in a FUSE file-system. This may be necessary when running Valgrind on a multi-threaded program that uses one thread to manage a FUSE file-system and another thread to access that file-system ๐Ÿฆ‹.
    • enable-outer: enables some special magic needed when the program being run is itself Valgrind ๐Ÿ‘‘ (yes, inception-core).
    • no-inner-prefix: disables printing a prefix > in front of each stdout or stderr output line in an inner Valgrind being run by an outer Valgrind. Super useful when running Valgrind regression tests in an outer/inner setup. Note that the prefix > will always be printed in front of the inner debug logging lines, no exceptions ๐Ÿ’….
    • no-nptl-pthread-stackcache: this hint is only relevant when running Valgrind on Linux; it is ignored on FreeBSD, Solaris and macOS.

The GNU glibc pthread library (libpthread.so), which pthread programs use, maintains a cache of pthread stacks ๐Ÿ“š. When a pthread terminates, the memory used for the pthread stack and some thread local storage related data structure are not always directly released. This memory is kept in a cache (up to a certain size) and is re-used if a new thread is started.

This cache causes the helgrind tool to report some false positive race condition errors on this cached memory, because helgrind does not understand the internal glibc cache synchronisation primitives ๐Ÿ˜ญ. So when using helgrind, disabling the cache helps avoid false positive race conditions โ€” in particular when using thread local storage variables (e.g. variables using the __thread qualifier).

When using the memcheck tool, disabling the cache ensures the memory used by glibc to handle __thread variables is directly released when a thread terminates โœจ.

Note: Valgrind disables the cache using some internal knowledge of the glibc stack cache implementation and by examining the debug information of the pthread library. This technique is thus somewhat fragile and might not work for all glibc versions. It has been successfully tested with various glibc versions (e.g. 2.11, 2.16, 2.18) on various platforms ๐Ÿ™ˆ.
  • lax-doors: (Solaris only) be very lax about door syscall handling over unrecognised door file descriptors. Does not require that full buffer is initialised when writing. Without this, programs using libdoor(3LIB) functionality with completely proprietary semantics may report a large number of false positives ๐Ÿ’€.
  • fallback-llsc: (MIPS and ARM64 only) enables an alternative implementation of Load-Linked (LL) and Store-Conditional (SC) instructions. The standard implementation gives more correct behaviour, but can cause indefinite looping on certain processor implementations that are intolerant of extra memory references between LL and SC. So far this is known only to happen on Cavium 3 cores. You should not need to use this flag, since the relevant cores are detected at startup and the alternative implementation is automatically enabled if necessary. There is no equivalent anti-flag โ€” you cannot force-disable the alternative implementation if it is automatically enabled ๐Ÿšซ. The underlying problem exists because the "standard" implementation of LL and SC is done by copying through LL and SC instructions into the instrumented code. However, tools may insert extra instrumentation memory references in between the LL and SC instructions. These memory references are not present in the original uninstrumented code, and their presence in the instrumented code can cause the SC instructions to persistently fail, leading to indefinite looping in LL-SC blocks ๐Ÿ˜ตโ€๐Ÿ’ซ. The alternative implementation gives correct behaviour of LL and SC instructions between threads in a process, up to and including the ABA scenario. It also gives correct behaviour between a Valgrinded thread and a non-Valgrinded thread running in a different process that communicate via shared memory โ€” but only up to and including correct CAS behaviour; in this case the ABA scenario may not be correctly handled ๐ŸŒˆ.

  • --scheduling-quantum=<number> [default: 100000] โ€” this one controls the maximum number of basic blocks a thread executes before releasing the lock Valgrind uses to serialise thread execution ๐ŸŽ€. Smaller values = finer interleaving but more scheduling overhead. Finer interleaving can be genuinely useful for reproducing race conditions with helgrind or DRD. For more details about the Valgrind thread serialisation scheme and its impact on performance and thread scheduling, see Scheduling and Multi-Thread Performance โญ.
  • --fair-sched=<no|yes|try> [default: no] โ€” controls the locking mechanism Valgrind uses to serialise thread execution ๐Ÿ”’. The locking mechanism controls the way threads get scheduled, and different settings give different trade-offs between fairness and performance. For more details about the Valgrind thread serialisation scheme and its impact on performance and thread scheduling, see Scheduling and Multi-Thread Performance.
    • --fair-sched=yes activates a fair scheduler. In short, if multiple threads are ready to run, they get scheduled in round robin fashion ๐ŸŽก. This mechanism is not available on all platforms or Linux versions. If not available, using --fair-sched=yes will cause Valgrind to terminate with an error ๐Ÿ’€. You may find this setting improves overall responsiveness if you're running an interactive multithreaded program โ€” for example a web browser โ€” on Valgrind ๐Ÿ‘‘.
    • --fair-sched=try activates fair scheduling if available on the platform. Otherwise it automatically falls back to --fair-sched=no ๐Ÿฆ‹.
    • --fair-sched=no activates a scheduler which does not guarantee fairness between threads ready to run, but which in general gives the highest performance ๐Ÿ”ฅ.
  • --kernel-variant=variant1,variant2,... โ€” handles system calls and ioctls arising from minor variants of the default kernel for this platform ๐ŸŒธ. Useful for running on hacked kernels or with kernel modules that support nonstandard ioctls, for example. Use with caution. If you don't understand what this option does then you almost certainly don't need it ๐Ÿ’…. Currently known variants are:
    • bproc: support the sys_broc system call on x86. This is for running on BProc, which is a minor variant of standard Linux sometimes used for building clusters ๐Ÿ–ฅ๏ธ.
  • android-no-hw-tls โ€” some versions of the Android emulator for ARM</p> just donโ€™t provide a hardware TLS (thread-local state) register, and Valgrind crashes at startup ๐Ÿ˜ญ. Use this variant to select software support for TLS.
  • android-gpu-sgx5xx โ€” use this to support handling of proprietary ioctls for the PowerVR SGX 5XX series of GPUs on Android devices โœจ. Failure to select this does not cause stability problems, but it may cause Memcheck to report false errors after the program performs GPU-specific ioctls.
  • android-gpu-adreno3xx โ€” similarly, use this to support handling of proprietary ioctls for the Qualcomm Adreno 3XX series of GPUs on Android devices ๐Ÿซถ.

๐ŸŒธ --merge-recursive-frames=<number> [default: 0] ๐ŸŒธ

Okay so some recursive algorithms โ€” think balanced binary tree implementations, for example โ€” create many different stack traces, and each one contains cycles of calls. A cycle is defined as two identical program counter values separated by zero or more other program counter values. Valgrind may then use a lot of memory to store all these stack traces ๐Ÿ˜ญ. Ngl thatโ€™s a poor use of memory, especially considering that such stack traces contain repeated uninteresting recursive calls instead of more interesting information, like the function that initiated the recursive call.

The option --merge-recursive-frames=<number> instructs Valgrind to detect and merge recursive call cycles having a size of up to <number> frames. When such a cycle is detected, Valgrind records the cycle in the stack trace as a unique program counter.

The value 0 (the default) causes no recursive call merging. A value of 1 will cause stack traces of simple recursive algorithms (for example, a factorial implementation) to be collapsed. A value of 2 will usually be needed to collapse stack traces produced by recursive algorithms such as binary trees, quick sort, etc. Higher values might be needed for more complex recursive algorithms.

๐Ÿ“ Note: recursive calls are detected by analysis of program counter values. They are not detected by looking at function names.

๐Ÿฆ‹ --num-transtab-sectors=<number> [default: 6 for Android platforms, 16 for all others] ๐Ÿฆ‹

Valgrind translates and instruments your programโ€™s machine code in small fragments (basic blocks). The translations are stored in a translation cache that is divided into a number of sections (sectors). If the cache is full, the sector containing the oldest translations is emptied and reused. If these old translations are needed again, Valgrind must re-translate and re-instrument the corresponding machine code, which is expensive ๐Ÿ’ธ. If the โ€œexecuted instructionsโ€ working set of a program is big, increasing the number of sectors may improve performance by reducing the number of re-translations needed.

Sectors are allocated on demand. Once allocated, a sector can never be freed, and it occupies considerable space, depending on the tool and the value of --avg-transtab-entry-size (about 40 MB per sector for Memcheck). Use the option --stats=yes to obtain precise information about the memory used by a sector and the allocation and recycling of sectors ๐Ÿ‘‘.

๐ŸŽ€ --avg-transtab-entry-size=<number> [default: 0, meaning use tool provided default] ๐ŸŽ€

Average size of translated basic block. This average size is used to dimension the size of a sector. Each tool provides a default value to be used. If this default value is too small, the translation sectors will become full too quickly ๐Ÿ˜ฌ. If this default value is too big, a significant part of the translation sector memory will be unused.

Note that the average size of a basic block translation depends on the tool, and it might depend on tool options. For example, the memcheck option --track-origins=yes increases the size of the basic block translations. Use --avg-transtab-entry-size to tune the size of the sectors, either to gain memory or to avoid too many retranslations โœจ.

๐Ÿ’œ --aspace-minaddr=<address> [default: depends on the platform] ๐Ÿ’œ

To avoid potential conflicts with some system libraries, Valgrind does not use the address space below --aspace-minaddr value, keeping it reserved in case a library specifically requests memory in this region. So, some โ€œpessimisticโ€ value is guessed by Valgrind depending on the platform. On linux, by default, Valgrind avoids using the first 64MB even if typically there is no conflict in this complete zone. You can use the option --aspace-minaddr to have your memory hungry application benefitting from more of this lower memory ๐Ÿ“. On the other hand, if you encounter a conflict, increasing aspace-minaddr value might solve it. Conflicts will typically manifest themselves with mmap failures in the low range of the address space.

The provided address must be page aligned and must be equal or bigger to 0x1000 (4KB). To find the default value on your platform, do something such as:

valgrind -d -d date 2>&1 | grep -i minaddr

Values lower than 0x10000 (64KB) are known to create problems on some distributions.

๐ŸŒˆ --valgrind-stacksize=<number> [default: 1MB] ๐ŸŒˆ

For each thread, Valgrind needs its own โ€œprivateโ€ stack. The default size for these stacks is largely dimensioned, and so should be sufficient in most cases. In case the size is too small, Valgrind will segfault ๐Ÿ’€. Before segfaulting, a warning might be produced by Valgrind when approaching the limit.

Use the option --valgrind-stacksize if such an (unlikely) warning is produced, or if Valgrind dies due to a segmentation violation. Such segmentation violations have been seen when demangling huge C++ symbols ๐Ÿ˜ญ.

If your application uses many threads and needs a lot of memory, you can gain some memory by reducing the size of these Valgrind stacks using the option --valgrind-stacksize ๐Ÿซถ.

โญ --show-emwarns=<yes|no> [default: no] โญ

When enabled, Valgrind will emit warnings about its CPU emulation in certain cases. These are usually not interesting ๐Ÿ™ˆ.

๐Ÿงš --require-text-symbol=:sonamepatt:fnnamepatt ๐Ÿงš

When a shared object whose soname matches sonamepatt is loaded into the process, examine all the text symbols it exports. If none of those match fnnamepatt, print an error message and abandon the run. This makes it possible to ensure that the run does not continue unless a given shared object contains a particular function name ๐Ÿ‘‘.

Both sonamepatt and fnnamepatt can be written using the usual ? and * wildcards. For example: ":*libc.so*:foo?bar". You may use characters other than a colon to separate the two patterns. It is only important that the first character and the separator character are the same. For example, the above example could also be written "Q*libc.so*Qfoo?bar". Multiple --require-text-symbol flags are allowed, in which case shared objects that are loaded into the process will be checked against all of them.

The purpose of this is to support reliable usage of marked-up libraries. For example, suppose we have a version of GCCโ€™s libgomp.so which has been marked up with annotations to support Helgrind. It is only too easy and confusing to load the wrong, un-annotated libgomp.so into the application ๐Ÿ˜ญ. So the idea is: add a text symbol in the marked-up library, for example annotated_for_helgrind_3_6, and then give the flag --require-text-symbol=:*libgomp*so*:annotated_for_helgrind_3_6 so that when libgomp.so is loaded, Valgrind scans its symbol table, and if the symbol isnโ€™t present the run is aborted, rather than continuing silently with the un-marked-up library. Note that you should put the entire flag in quotes to stop shells expanding up the * and ? wildcards.

๐Ÿ’… --soname-synonyms=syn1=pattern1,syn2=pattern2,... ๐Ÿ’…

When a shared library is loaded, Valgrind checks for functions in the library that must be replaced or wrapped. For example, Memcheck replaces some string and memory functions (strchr, strlen, strcpy, memchr, memcpy, memmove, etc.) with its own versions. Such replacements are normally done only in shared libraries whose soname matches a predefined soname pattern (e.g. libc.so* on linux). By default, no replacement is done for a statically linked binary or for alternative libraries, except for the allocation functions (malloc, free, calloc, memalign, realloc, operator new, operator delete, etc.) Such allocation functions are intercepted by default in any shared library or in the executable if they are exported as global symbols. This means that if a replacement allocation library such as tcmalloc is found, its functions are also intercepted by default.

In some cases, the replacements allow --soname-synonyms to specify one additional synonym pattern, giving flexibility in the replacement. Or to prevent interception of all public allocation symbols.

Currently, this flexibility is only allowed for the malloc related functions, using the synonym somalloc. This synonym is usable for all tools doing standard replacement of malloc related functions (e.g. memcheck, helgrind, drd, massif, dhat).

  • Alternate malloc library โ€” to replace the malloc related functions in a specific alternate library with soname mymalloclib.so (and not in any others), give the option --soname-synonyms=somalloc=mymalloclib.so. A pattern can be used to match multiple libraries sonames. For example, --soname-synonyms=somalloc=*tcmalloc* will match the soname of all variants of the tcmalloc library (native, debug, profiled, ... tcmalloc variants). Note: the soname of an ELF shared library can be retrieved using the readelf utility.
  • Replacements in a statically linked library โ€” these are done by using the NONE pattern. For example, if you link with libtcmalloc.a, and only want to intercept the malloc related functions in the executable (and standard libraries) themselves, but not any other shared libraries, you can give the option --soname-synonyms=somalloc=NONE. Note that a NONE pattern will match the main executable and any shared library having no soname.
  • To only intercept allocation symbols in the default system libraries, but not in any other shared library or the executable defining public malloc or operator new related functions, use a non-existing library name like --soname-synonyms=somalloc=nouserintercepts (where nouserintercepts can be literally any non-existing library name, bestie, the name itself is not that deep).
    • The shared library of the dynamic (runtime) linker is excluded from searching for global public symbols, such as those for the malloc related functions (identified by the somalloc synonym). Lowkey exclusion era ๐Ÿšซ
  • --progress-interval=<number> [default: 0, meaning 'disabled'] โ€” okay so this one is a glow-up for Valgrind's own debugging output, and ngl it's probably not gonna be your vibe as a regular end user ๐Ÿ™ˆ

When number is set to a non-zero value, Valgrind will print a one-line progress summary every number seconds. Valid settings for number are between 0 and 3600 inclusive. Here's some example output with number set to 10:

PROGRESS: U 110s, W 113s, 97.3% CPU, EvC 414.79M, TIn 616.7k, TOut 0.5k, #thr 67
PROGRESS: U 120s, W 124s, 96.8% CPU, EvC 505.27M, TIn 636.6k, TOut 3.0k, #thr 64
PROGRESS: U 130s, W 134s, 97.0% CPU, EvC 574.90M, TIn 657.5k, TOut 3.0k, #thr 63

Each line shows:

  • U: total user time
  • W: total wallclock time
  • CPU: overall average cpu use
  • EvC: number of event checks. An event check is a backwards branch in the simulated program, so this is a measure of forward progress of the program
  • TIn: number of code blocks instrumented by the JIT
  • TOut: number of instrumented code blocks that have been thrown away
  • #thr: number of threads in the program

From the progress of these, it is possible to observe:

  • when the program is compute bound (TIn rises slowly, EvC rises rapidly)
  • when the program is in a spinloop (TIn/TOut fixed, EvC rises rapidly)
  • when the program is JIT-bound (TIn rises rapidly)
  • when the program is rapidly discarding code (TOut rises rapidly)
  • when the program is about to achieve some expected state (EvC arrives at some value you expect)
  • when the program is idling (U rises more slowly than W)

๐Ÿ› ๏ธ DEBUGGING VALGRIND OPTIONS ๐Ÿ› ๏ธ

There are also some options for debugging Valgrind itself. Fr fr you shouldn't need to use them in the normal run of things โ€” they're like, backstage passes, not for the general public ๐Ÿ’… If you wish to see the list, use the --help-debug option.


๐Ÿง  MEMCHECK OPTIONS ๐Ÿง 

  • --leak-check=<no|summary|yes|full> [default: summary] โ€” when enabled, search for memory leaks when the client program finishes. If set to summary, it says how many leaks occurred. If set to full or yes, each individual leak will be shown in detail and/or counted as an error, as specified by the options --show-leak-kinds and --errors-for-leak-kinds. She's thorough, okay? ๐Ÿ’–

If --xml=yes is given, memcheck will automatically use the value --leak-check=full. You can use --show-leak-kinds=none to reduce the size of the xml output if you are not interested in the leak results. Iconic size-shrinking behaviour โœจ

  • --leak-resolution=<low|med|high> [default: high] โ€” when doing leak checking, determines how willing Memcheck is to consider different backtraces to be the same for the purposes of merging multiple leaks into a single leak report. When set to low, only the first two entries need match. When med, four entries have to match. When high, all entries need to match. Basically how picky is she about calling two things "the same leak" ๐ŸŽ€

For hardcore leak debugging, you probably want to use --leak-resolution=high together with --num-callers=40 or some such large number.

Note that the --leak-resolution setting does not affect Memcheck's ability to find leaks. It only changes how the results are presented. Aesthetic choices only, no cap ๐Ÿ’…

  • --show-leak-kinds=<set> [default: definite,possible] โ€” specifies the leak kinds to show in a full leak search, in one of the following ways:
    • a comma separated list of one or more of definite indirect possible reachable.
    • all to specify the complete set (all leak kinds). It is equivalent to --show-leak-kinds=definite,indirect,possible,reachable.
    • none for the empty set.
  • --errors-for-leak-kinds=<set> [default: definite,possible] โ€” specifies the leak kinds to count as errors in a full leak search. The <set> is specified similarly to --show-leak-kinds. Same rules, different consequence โ€” these ones actually get counted as errors ๐Ÿ˜ญ
  • --leak-check-heuristics=<set> [default: all] โ€” specifies the set of leak check heuristics to be used during leak searches. The heuristics control which interior pointers to a block cause it to be considered as reachable. The heuristic set is specified in one of the following ways:
    • a comma separated list of one or more of stdstring length64 newarray multipleinheritance.
    • all to activate the complete set of heuristics. It is equivalent to --leak-check-heuristics=stdstring,length64,newarray,multipleinheritance.
    • none for the empty set.
Note that these heuristics are dependent on the layout of the objects produced by the C++ compiler. They have been tested with some gcc versions (e.g. 4.4 and 4.7). They might not work properly with other C++ compilers. โš ๏ธ So like, don't come for her if your compiler does funky things.
  • --show-reachable=<yes|no> , --show-possibly-lost=<yes|no> โ€” these options provide an alternative way to specify the leak kinds to show:
    • --show-reachable=no --show-possibly-lost=yes is equivalent to --show-leak-kinds=definite,possible.
    • --show-reachable=no --show-possibly-lost=no is equivalent to --show-leak-kinds=definite.
    • --show-reachable=yes is equivalent to --show-leak-kinds=all.

Note that --show-possibly-lost=no has no effect if --show-reachable=yes is specified. She said what she said ๐Ÿซถ

  • --xtree-leak=<no|yes> [no] โ€” if set to yes, the results for the leak search done at exit will be output in a 'Callgrind Format' execution tree file. Note that this automatically sets the options --leak-check=full and --show-leak-kinds=all, to allow xtree visualisation tools such as kcachegrind to select what kind to leak to visualize. The produced file will contain the following events:
    • RB : Reachable Bytes
    • PB : Possibly lost Bytes
    • IB : Indirectly lost Bytes
    • DB : Definitely lost Bytes (direct plus indirect)
    • DIB : Definitely Indirectly lost Bytes (subset of DB)
    • RBk : reachable Blocks
    • PBk : Possibly lost Blocks
    • IBk : Indirectly lost Blocks
    • DBk : Definitely lost Blocks

The increase or decrease for all events above will also be output in the file to provide the delta (increase or decrease) between 2 successive leak searches. For example, iRB is the increase of the RB event, dPBk is the decrease of PBk event. The values for the increase and decrease events will be zero for the first leak search done. Math girlie era ๐Ÿงฎโœจ

See Execution Trees for a detailed explanation about execution trees.

  • --xtree-leak-file=<filename> [default: xtleak.kcg.%p] โ€” specifies that Valgrind should produce the xtree leak report in the specified file. Any %p, %q or %n sequences appearing in the filename are expanded in exactly the same way as they are for --log-file. See the description of --log-file for details.

See Execution Trees for a detailed explanation about execution trees formats.

  • --undef-value-errors=<yes|no> [default: yes] โ€” controls whether Memcheck reports uses of undefined value errors. Set this to no if you don't want to see undefined value errors. It also has the side effect of speeding up Memcheck somewhat. Speedy queen ๐Ÿƒโ€โ™€๏ธ๐Ÿ’จ AddrCheck (removed in Valgrind 3.1.0) functioned like Memcheck with --undef-value-errors=no. RIP bozo ๐Ÿชฆ
  • --track-origins=<yes|no> [default: no] โ€” controls whether Memcheck tracks the origin of uninitialised values. By default, it does not, which means that although it can tell you that an uninitialised value is being used in a dangerous way, it cannot tell you where the uninitialised value came from. This often makes it difficult to track down the root problem. It's giving "I know something's wrong but I don't know why" ๐Ÿ˜ญ

When set to yes, Memcheck keeps track of the origins of all uninitialised values. Then, when an uninitialised value error is reported, Memcheck will try to show the origin of the value. An origin can be one of the following four places: a heap block, a stack allocation, a client request, or miscellaneous other sources (eg, a call to brk).

For uninitialised values originating from a heap block, Memcheck shows where the block was allocated. For uninitialised values originating from a stack allocation, Memcheck can tell you which function allocated the value, but no more than that โ€” typically it shows you the source location of the opening brace of the function. So you should carefully check that all of the function's local variables are initialised properly. Bestie, pls initialise your locals, I'm begging ๐Ÿ™

Performance overhead: origin tracking is expensive. It halves Memcheck's speed and increases memory use by a minimum of 100MB, and possibly more. Nevertheless it can drastically reduce the effort required to identify the root cause of uninitialised value errors, and so is often a programmer productivity win, despite running more slowly. Trade-off central ๐Ÿ’…

Accuracy: Memcheck tracks origins quite accurately. To avoid very large space and time overheads, some approximations are made. It is possible, although unlikely, that Memcheck will report an incorrect origin, or not be able to identify any origin.

Note that the combination --track-origins=yes and --undef-value-errors=no is nonsensical. Memcheck checks for and rejects this combination at startup. She's not even gonna entertain it ๐Ÿ’€
  • --partial-loads-ok=<yes|no> [default: yes] โ€” controls how Memcheck handles 32-, 64-, 128- and 256-bit naturally aligned loads from addresses for which some bytes are addressable and others are not. When yes, such loads do not produce an address error. Instead, loaded bytes originating from illegal addresses are marked as uninitialised, and those corresponding to legal addresses are handled in the normal way.

When no, loads from partially invalid addresses are treated the same as loads from completely invalid addresses: an illegal-address error is issued, and the resulting bytes are marked as initialised.

Note that code that behaves in this way is in violation of the ISO C/C++ standards, and should be considered broken. If at all possible, such code should be fixed. ๐Ÿšจ Like, fr fr fix it, this is not the flex you think it is.
  • --expensive-definedness-checks=<no|auto|yes> โ€” [default: auto] ๐Ÿ’œ so this one controls whether Memcheck does the more precise (and also more expensive, as in time-consuming ๐Ÿ˜ญ) instrumentation when it's checking the definedness of certain values. Specifically it affects how integer adds, subtracts and equality comparisons get instrumented.

Okay so pick --expensive-definedness-checks=yes and Memcheck uses the most accurate analysis possible. Bestie, it minimises false error rates, but it can cause up to 30% performance degradation. Yep, thirty. ๐Ÿ’€

Pick --expensive-definedness-checks=no and Memcheck uses the cheapest instrumentation possible. Max performance, but it will normally give an unusably high false error rate. Like, unusably. Not the vibe. ๐Ÿ™ˆ

The default, --expensive-definedness-checks=auto, is strongly recommended. It makes Memcheck use the minimum of expensive instrumentation needed to hit the same false error rate as --expensive-definedness-checks=yes. It also turns on an instrumentation-time analysis pass that aims to further reduce the costs of accurate instrumentation. Overall the performance loss is generally around 5% relative to --expensive-definedness-checks=no, although this is strongly workload dependent. Note that the exact instrumentation settings in this mode are architecture dependent. ๐ŸŒˆ

  • --keep-stacktraces=alloc|free|alloc-and-free|alloc-then-free|none โ€” [default: alloc-and-free] โœจ controls which stack trace(s) to keep for malloc'd and/or free'd blocks.

With alloc-then-free, a stack trace is recorded at allocation time and is associated with the block. When the block is freed, a second stack trace is recorded, and this replaces the allocation stack trace. As a result, any "use after free" errors relating to this block can only show a stack trace for where the block was freed.

With alloc-and-free, both the allocation and the deallocation stack traces for the block are stored. So a "use after free" error will show both, which may make the error easier to diagnose. Compared to alloc-then-free, this setting slightly increases Valgrind's memory use as the block contains two references instead of one.

With alloc, only the allocation stack trace is recorded (and reported). With free, only the deallocation stack trace is recorded (and reported). These values somewhat decrease Valgrind's memory and cpu usage. They can be useful depending on the error types you are searching for and the level of detail you need to analyse them. For example, if you are only interested in memory leak errors, it is sufficient to record the allocation stack traces. ๐Ÿซถ

With none, no stack traces are recorded for malloc and free operations. If your program allocates a lot of blocks and/or allocates/frees from many different stack traces, this can significantly decrease cpu and/or memory required. Of course, few details will be reported for errors related to heap blocks.

Note that once a stack trace is recorded, Valgrind keeps the stack trace in memory even if it is not referenced by any block. ๐Ÿ‘€ Some programs (for example, recursive algorithms) can generate a huge number of stack traces. If Valgrind uses too much memory in such circumstances, you can reduce the memory required with the options --keep-stacktraces and/or by using a smaller value for the option --num-callers.

If you want to use --xtree-memory=full memory profiling (see Execution Trees), then you cannot specify --keep-stacktraces=free or --keep-stacktraces=none. That's just how it is, bestie. ๐Ÿ’…

  • --freelist-vol=<number> โ€” [default: 20000000] ๐ŸŽ€ When the client program releases memory using free (in C) or delete (C++), that memory is not immediately made available for re-allocation. Instead, it's marked inaccessible and placed in a queue of freed blocks. The purpose is to defer as long as possible the point at which freed-up memory comes back into circulation. This increases the chance that Memcheck will be able to detect invalid accesses to blocks for some significant period of time after they've been freed. Iconic behaviour, honestly. ๐Ÿ‘‘

This option specifies the maximum total size, in bytes, of the blocks in the queue. The default value is twenty million bytes. Increasing this increases the total amount of memory used by Memcheck but may detect invalid uses of freed blocks which would otherwise go undetected. ๐Ÿ”ฅ

  • --freelist-big-blocks=<number> โ€” [default: 1000000] ๐ŸŒธ When making blocks from the queue of freed blocks available for re-allocation, Memcheck will in priority re-circulate the blocks with a size greater or equal to --freelist-big-blocks. This ensures that freeing big blocks (in particular freeing blocks bigger than --freelist-vol) does not immediately lead to a re-circulation of all (or a lot of) the small blocks in the free list. In other words, this option increases the likelihood to discover dangling pointers for the "small" blocks, even when big blocks are freed. ๐Ÿฆ‹

Setting a value of 0 means that all the blocks are re-circulated in a FIFO order.

  • --workaround-gcc296-bugs=<yes|no> โ€” [default: no] ๐Ÿ’€ When enabled, assume that reads and writes some small distance below the stack pointer are due to bugs in GCC 2.96, and does not report them. The "small distance" is 256 bytes by default. Note that GCC 2.96 is the default compiler on some ancient Linux distributions (RedHat 7.X) and so you may need to use this option. Do not use it if you do not have to, as it can cause real errors to be overlooked. A better alternative is to use a more recent GCC in which this bug is fixed. ๐Ÿ™

You may also need to use this option when working with GCC 3.X or 4.X on 32-bit PowerPC Linux. This is because GCC generates code which occasionally accesses below the stack pointer, particularly for floating-point to/from integer conversions. This is in violation of the 32-bit PowerPC ELF specification, which makes no provision for locations below the stack pointer to be accessible. ๐Ÿ˜ญ

This option is deprecated as of version 3.12 and may be removed from future versions. You should instead use --ignore-range-below-sp to specify the exact range of offsets below the stack pointer that should be ignored. A suitable equivalent is --ignore-range-below-sp=1024-1.
  • --ignore-range-below-sp=<number>-<number> โ€” โญ this is a more general replacement for the deprecated --workaround-gcc296-bugs option (told you it was deprecated, bestie). When specified, it causes Memcheck not to report errors for accesses at the specified offsets below the stack pointer. The two offsets must be positive decimal numbers and โ€” somewhat counterintuitively โ€” the first one must be larger, in order to imply a non-wraparound address range to ignore. For example, to ignore 4 byte accesses at 8192 bytes below the stack pointer, use --ignore-range-below-sp=8192-8189. Only one range may be specified. ๐Ÿ’…
  • --show-mismatched-frees=<yes|no> โ€” [default: yes] ๐Ÿงš When enabled, Memcheck checks that heap blocks are deallocated using a function that matches the allocating function. That is, it expects free to be used to deallocate blocks allocated by malloc, delete for blocks allocated by new, and delete[] for blocks allocated by new[]. If a mismatch is detected, an error is reported. This is in general important because in some environments, freeing with a non-matching function can cause crashes. ๐Ÿ˜ฌ

There is however a scenario where such mismatches cannot be avoided. That is when the user provides implementations of new/new[] that call malloc and of delete/delete[] that call free, and these functions are asymmetrically inlined. For example, imagine that delete[] is inlined but new[] is not. The result is that Memcheck "sees" all delete[] calls as direct calls to free, even when the program source contains no mismatched calls.

This causes a lot of confusing and irrelevant error reports. --show-mismatched-frees=no disables these checks. It is not generally advisable to disable them, though, because you may miss real errors as a result. ๐Ÿ™ˆ

  • --show-realloc-size-zero=<yes|no> โ€” [default: yes] ๐Ÿ“ When enabled, Memcheck checks for uses of realloc with a size of zero. This usage of realloc is unsafe since it is not portable. On some systems it will behave like free. On other systems it will either do nothing or else behave like a call to free followed by a call to malloc with a size of zero. Chaos behaviour fr fr. ๐Ÿ’€
  • --ignore-ranges=0xPP-0xQQ[,0xRR-0xSS] โ€” ๐ŸŒˆ any ranges listed in this option (and multiple ranges can be specified, separated by commas) will be ignored by Memcheck's addressability checking. Slay, ignore them. โœจ
  • --malloc-fill=<hexnumber> โ€” ๐ŸŽ€ fills blocks allocated by malloc, new, etc, but not by calloc, with the specified byte. This can be useful when trying to shake out obscure memory corruption problems. The allocated area is still regarded by Memcheck as undefined โ€” this option only affects its contents. Note that --malloc-fill does not affect a block of memory when it is used as argument to client requests VALGRIND_MEMPOOL_ALLOC or VALGRIND_MALLOCLIKE_BLOCK. ๐Ÿ‘‘
  • --free-fill=<hexnumber> โ€” ๐Ÿ’– fills blocks freed by free, delete, etc, with the specified byte value. This can be useful when trying to shake out obscure memory corruption problems. The freed area is still regarded by Memcheck as not valid for access โ€” this option only affects its contents. Note that --free-fill does not affect a block of memory when it is used as argument to client requests VALGRIND_MEMPOOL_FREE or VALGRIND_FREELIKE_BLOCK. ๐Ÿซถ

โœจ CACHEGRIND OPTIONS โœจ

Cachegrind is the cache girlie of the Valgrind fam โ€” she's counting every single time your code fumbles a cache line, and honestly? She's judging (lovingly). ๐ŸŽ€

  • --cachegrind-out-file=<file> โ€” write the Cachegrind output file to file instead of the default output file, cachegrind.out.<pid>. The %p and %q format specifiers can be used to embed the process ID and/or the contents of an environment variable in the name, same way it works for the core option --log-file. ๐Ÿ’…
  • --cache-sim=no|yes [no] โ€” turns collection of cache access and miss counts on or off. Default is no, bestie โ€” it's off unless you say otherwise.
  • --branch-sim=no|yes [no] โ€” turns collection of branch instruction and misprediction counts on or off. Also defaults to no.
  • --instr-at-start=no|yes [yes] โ€” enables or disables instrumentation at the start of execution. Use this in combination with CACHEGRIND_START_INSTRUMENTATION and CACHEGRIND_STOP_INSTRUMENTATION to measure only part of a client program's execution. Cherry-picking your data collection era, we love to see it ๐Ÿ“
  • --I1=<size>,<associativity>,<line size> โ€” specify the size, associativity and line size of the level 1 instruction cache. Only useful with --cache-sim=yes.
  • --D1=<size>,<associativity>,<line size> โ€” specify the size, associativity and line size of the level 1 data cache. Only useful with --cache-sim=yes.
  • --LL=<size>,<associativity>,<line size> โ€” specify the size, associativity and line size of the last-level cache. Only useful with --cache-sim=yes.
๐Ÿ’€ Real talk: all three of those cache-shape options only do anything when --cache-sim=yes is on. Setting them otherwise is giving "decorating an empty room."

๐ŸŒˆ CALLGRIND OPTIONS ๐ŸŒˆ

Callgrind is the receipts tool โ€” she keeps a whole paper trail of where all your time went, and there's a lot of knobs to turn. Buckle in, bestie, this list is long but every single one is here. ๐Ÿซถ

  • --callgrind-out-file=<file> โ€” write the profile data to file rather than to the default output file, callgrind.out.<pid>. The %p and %q format specifiers can be used to embed the process ID and/or the contents of an environment variable in the name, as is the case for the core option --log-file. When multiple dumps are made, the file name is modified further; see below. ๐Ÿ‘‘
  • --dump-line=<no|yes> [default: yes] โ€” specifies that event counting should be performed at source line granularity. This allows source annotation for sources which are compiled with debug information (-g). So likeโ€ฆ turn on -g or this doesn't eat ๐Ÿ’…
  • --dump-instr=<no|yes> [default: no] โ€” specifies that event counting should be performed at per-instruction granularity. This allows for assembly code annotation. Currently the results can only be displayed by KCachegrind. Yeah, sorry, only KCachegrind understood that vibe check.
  • --compress-strings=<no|yes> [default: yes] โ€” this option influences the output format of the profile data. It specifies whether strings (file and function names) should be identified by numbers. This shrinks the file, but makes it more difficult for humans to read (which is not recommended in any case). Lowkey a tradeoff between small file and readable file, and the manpage is firmly on the "readable" side ๐Ÿ™ˆ
  • --compress-pos=<no|yes> [default: yes] โ€” this option influences the output format of the profile data. It specifies whether numerical positions are always specified as absolute values or are allowed to be relative to previous numbers. This shrinks the file size. Small file, icon behaviour โœจ
  • --combine-dumps=<no|yes> [default: no] โ€” when enabled, when multiple profile data parts are to be generated these parts are appended to the same output file. Not recommended. I said what I said.
  • --dump-every-bb=<count> [default: 0, never] โ€” dump profile data every count basic blocks. Whether a dump is needed is only checked when Valgrind's internal scheduler is run. Therefore, the minimum setting useful is about 100000. The count is a 64-bit value to make long dump periods possible. So like, 0 means never, and if you set it to 3 you're just gonna get vibes and no dumps fr fr.
  • --dump-before=<function> โ€” dump when entering function.
  • --zero-before=<function> โ€” zero all costs when entering function.
  • --dump-after=<function> โ€” dump when leaving function.
  • --instr-atstart=<yes|no> [default: yes] โ€” specify if you want Callgrind to start simulation and profiling from the beginning of the program.

When set to no, Callgrind will not be able to collect any information, including calls, but it will have at most a slowdown of around 4, which is the minimum Valgrind overhead. Instrumentation can be interactively enabled via callgrind_control -i on.

Note that the resulting call graph will most probably not contain main, but will contain all the functions executed after instrumentation was enabled. Instrumentation can also be programmatically enabled/disabled. See the Callgrind include file callgrind.h for the macro you have to use in your source code.

For cache simulation, results will be less accurate when switching on instrumentation later in the program run, as the simulator starts with an empty cache at that moment. Switch on event collection later to cope with this error. ๐Ÿ˜ญ So like, don't switch it on halfway and then act surprised when the numbers look weird.

  • --collect-atstart=<yes|no> [default: yes] โ€” specify whether event collection is enabled at beginning of the profile run.

To only look at parts of your program, you have two possibilities:

  1. Zero event counters before entering the program part you want to profile, and dump the event counters to a file after leaving that program part.
  2. Switch on/off collection state as needed to only see event counters happening while inside of the program part you want to profile.

The second option can be used if the program part you want to profile is called many times. Option 1, i.e. creating a lot of dumps is not practical here. Like, imagine dumping a million times โ€” that's giving chaos, not giving results ๐Ÿ’€

Collection state can be toggled at entry and exit of a given function with the option --toggle-collect. If you use this option, collection state should be disabled at the beginning. Note that the specification of --toggle-collect implicitly sets --collect-state=no.

Collection state can be toggled also by inserting the client request CALLGRIND_TOGGLE_COLLECT ; at the needed code positions. Yes, with the semicolon, keep it exactly like that, it's part of the fit ๐Ÿ’…

  • --toggle-collect=<function> โ€” toggle collection on entry/exit of function.
  • --collect-jumps=<no|yes> [default: no] โ€” this specifies whether information for (conditional) jumps should be collected. As above, callgrind_annotate currently is not able to show you the data. You have to use KCachegrind to get jump arrows in the annotated code. ๐Ÿน
  • --collect-systime=<no|yes|msec|usec|nsec> [default: no] โ€” this specifies whether information for system call times should be collected.

The value no indicates to record no system call information.

The other values indicate to record the number of system calls done (sysCount event) and the elapsed time (sysTime event) spent in system calls. The --collect-systime value gives the unit used for sysTime: milli seconds, micro seconds or nano seconds. With the value nsec, callgrind also records the cpu time spent during system calls (sysCpuTime).

The value yes is a synonym of msec. The value nsec is not supported on Darwin. ๐ŸŽ Sorry Apple besties, nsec said "not today."

  • --collect-bus=<no|yes> [default: no] โ€” this specifies whether the number of global bus events executed should be collected. The event type "Ge" is used for these events.
  • --cache-sim=<yes|no> [default: no] โ€” specify if you want to do full cache simulation. By default, only instruction read accesses will be counted ("Ir"). With cache simulation, further event counters are enabled: Cache misses on instruction reads ("I1mr"/"ILmr"), data read accesses ("Dr") and related cache misses ("D1mr"/"DLmr"), data write accesses ("Dw") and related cache misses ("D1mw"/"DLmw"). For more information, see Cachegrind: a cache and branch-prediction profiler. ๐Ÿงš
  • --branch-sim=<yes|no> [default: no] โ€” specify if you want to do branch prediction simulation. Further event counters are enabled: Number of executed conditional branches and related predictor misses ("Bc"/"Bcm"), executed indirect jumps and related misses of the jump address predictor ("Bi"/"Bim"). ๐Ÿ”ฅ
โญ Heads up: --cache-sim and --branch-sim here are the Callgrind versions โ€” same spelling as the Cachegrind ones but living their own separate main character life in this tool. Don't mix up the receipts.

โœจ HELGRIND OPTIONS โœจ

Okay bestie, these are all the knobs Helgrind (the thread-error detector tool) lets you twist. There are a lot of them, so buckle up ๐ŸŽ€


  • --free-is-write=no|yes [default: no] โ€” when you turn this on (it's not the default, just so we're clear), Helgrind treats freeing heap memory like the memory got written right before the free happened. Why do we care? Because it flushes out races where one thread is referencing some memory and another thread frees it, but there's no visible synchronisation event making sure the reference happens before the free. Sneaky little gremlins ๐Ÿ™ˆ

Heads up: this feature is new in Valgrind 3.7.0 and it's considered experimental. It's off by default because nobody really fully understands how it interacts with custom memory allocators yet. The devs literally welcome your feedback ๐Ÿซถ

  • --track-lockorders=no|yes [default: yes] โ€” when enabled (which it is, by default), Helgrind does lock order consistency checking, i.e. it catches you taking locks in a sketchy order. The thing is, on some truly buggy programs you'll get so many lock order errors that it becomes genuinely annoying ๐Ÿ˜ญ especially if you only actually care about race errors. In that case, disabling lock order checking is lowkey a solid move.
  • --history-level=none|approx|full [default: full] โ€” this one's a whole spectrum, so let's break it down:

--history-level=full (the default!) makes Helgrind collect enough info about "old" accesses that it can give you two stack traces in a race report โ€” one for the current access, and one for the older conflicting access. To keep memory usage from going feral, the "old" access stack traces are capped at a max of --history-backtrace-size entries (default 8), or at the --num-callers value if that one's smaller.

Collecting all that info is expensive โ€” in speed and memory โ€” especially for programs doing tons of inter-thread synchronisation events (locks, unlocks, etc.). But without it, tracking down the root cause of a race is way harder. That said, you might not need it if you're just checking whether races exist at all โ€” like when you're regression testing a program that used to be race-free ๐Ÿ’…

--history-level=none is the total opposite extreme. Helgrind collects zero info about previous accesses. This can be dramatically faster than --history-level=full ๐Ÿ”ฅ

--history-level=approx is the compromise. You get a full trace for the later access, plus approximate info for the earlier one. That approximate info is two stacks, and the earlier access is guaranteed to have happened somewhere between the program points those two stacks denote. Not as iconic as showing the exact stack for the previous access (like --history-level=full does), but way better than nothing โ€” and it's almost as fast as --history-level=none.

  • --history-backtrace-size=<number> [default: 8] โ€” when --history-level=full is selected, --history-backtrace-size=number tells Helgrind how many entries to record in "old" access stack traces.
  • --delta-stacktrace=no|yes [default: yes on linux amd64/x86] โ€” this flag does absolutely nothing unless you're at --history-level=full, okay?

It configures how Helgrind captures stacktraces for --history-level=full. And bestie, such a stacktrace is typically needed every single time a new piece of memory gets read or written in a basic block of instructions ๐Ÿ‘€

--delta-stacktrace=no makes Helgrind compute a full history stacktrace from the unwind info each and every time a stacktrace is needed.

--delta-stacktrace=yes tells Helgrind to derive a new stacktrace from the previous one โ€” as long as there was no call instruction, no return instruction, or any other instruction changing the call stack since the last stacktrace was captured. If no such instruction ran, the new stacktrace can just be derived from the previous one by changing the top frame to the current program counter. This can speed Helgrind up by 25% when using --history-level=full โšก

But here's the tea, you gotta consider these things when using --delta-stacktrace=yes:

  • In some cases (like inside a function prologue), the valgrind unwinder might not properly unwind the stack, because of limitations and/or wrong unwind info. With --delta-stacktrace=yes, that wrong stack trace captured in the function prologue sticks around till the next call or return ๐Ÿ’€
  • On the flip side, --delta-stacktrace=yes sometimes helps you get a correct stacktrace โ€” for example when the unwind info allows a correct stacktrace at the beginning of the instruction sequence but not later on in it.
  • Figuring out which instructions are changing the callstack is partially based on platform dependent heuristics, which have to be tuned/validated specifically for the platform. Also, unwinding in a function prologue has to be good enough to allow --delta-stacktrace=yes. Currently, --delta-stacktrace=yes has only been reasonably validated on linux x86 32 bits and linux amd64 64 bits. For the details on how to validate it, peep the debug option --hg-sanity-flags and the function check_cached_rcec_ok in libhb_core.c.
  • --conflict-cache-size=N [default: 1000000] โ€” again, this flag only does anything at --history-level=full.

Info about "old" conflicting accesses lives in a cache of limited size, managed LRU-style. This is necessary because storing a stack trace for literally every single memory access the program makes just isn't practical. Historical info on locations that haven't been accessed recently gets periodically discarded to free up space in the cache ๐Ÿ—‘๏ธ

This option controls the cache size, measured in the number of different memory addresses for which conflicting access info is stored. If Helgrind is showing race errors with only one stack instead of the two you expected, try bumping this value up.

Minimum is 10,000 and maximum is 30,000,000 (thirty times the default). Raising the value by 1 increases Helgrind's memory requirement by very roughly 100 bytes, so the max value will easily munch up three extra gigabytes or so of memory ๐Ÿ˜ญ

  • --check-stack-refs=no|yes [default: yes] โ€” by default Helgrind checks all data memory accesses your program makes. This flag lets you skip checking for accesses to thread stacks (local variables). It can improve performance, but the cost is missing races on stack-allocated data. Trade-offs, bestie ๐ŸŒธ
  • --ignore-thread-creation=<yes|no> [default: no] โ€” controls whether all activity during thread creation gets ignored. By default it's only enabled on Solaris. See, Solaris provides higher throughput, parallelism and scalability than other operating systems, at the cost of more fine-grained locking activity. So for example, under glibc when a thread is created, just one big lock is used for all thread setup. Solaris libc uses several fine-grained locks, and the creator thread resumes its activities ASAP โ€” leaving stuff like stack and TLS setup sequence to the created thread. That situation confuses Helgrind, because it assumes there's some false ordering in place between the creator and the created thread, and therefore many types of race conditions in the application wouldn't get reported ๐Ÿšฉ To prevent that false ordering, this command line option is set to yes by default on Solaris. All activity (loads, stores, client requests) is therefore ignored during:
    • the pthread_create() call in the creator thread
    • the thread creation phase (stack and TLS setup) in the created thread

Also, new memory allocated during thread creation is untracked, meaning race reporting is suppressed there. DRD does the same thing implicitly. This is necessary because Solaris libc caches many objects and reuses them for different threads, and that confuses Helgrind.

  • --show-events=0|1|2 [default: 0] โ€” controls tracing of internal Helgrind synchronization, threading and memory events. At level 1, Helgrind prints a trace of its synchronization, threading and memory events. At level 2, additional memory events get traced too. The default value of 0 disables tracing entirely.
  • --track-destroy=no|yes|all [default: no] โ€” controls checking for missing pthread_mutex_destroy and pthread_rwlock_destroy calls. With yes, Helgrind warns that a destroy call is missing when pthread_mutex_init or pthread_rwlock_init is called on an address that already has a live lock record ๐Ÿ‘€ With all, Helgrind reports at process exit every mutex and rwlock that was explicitly initialized but never destroyed. Locks that weren't explicitly initialized (like the ones using static initializers such as PTHREAD_MUTEX_INITIALIZER) don't get reported. The default value of no disables tracking.

โœจ DRD OPTIONS โœจ

Okay bestie, these are the DRD tool options, and they're giving โ€œdata-race detective with a very cute clipboard.โ€ ๐Ÿ•ต๏ธโ€โ™€๏ธ๐Ÿ’… Every default is right here, so you can vibe-check each one before you flip it.

  • --check-stack-var=<yes|no> [default: no] โ€” Controls whether DRD detects data races on stack variables. Verifying stack variables is disabled by default because most programs do not share stack variables over threads. makes sense, honestly ๐Ÿ’–
  • --exclusive-threshold=<n> [default: off] โ€” Print an error message if any mutex or writer lock has been held longer than the time specified in milliseconds. This option enables the detection of lock contention. lock held too long? caught in 4K ๐Ÿ”ฅ
  • --join-list-vol=<n> [default: 10] โ€” Data races that occur between a statement at the end of one thread and another thread can be missed if memory access information is discarded immediately after a thread has been joined. This option allows one to specify for how many joined threads memory access information should be retained. keep the receipts for a bit ๐Ÿงพ
  • --first-race-only=<yes|no> [default: no] โ€” Whether to report only the first data race that has been detected on a memory location or all data races that have been detected on a memory location. one warning or the whole group chat? your call ๐Ÿ’œ
  • --free-is-write=<yes|no> [default: no] โ€” Whether to report races between accessing memory and freeing memory. Enabling this option may cause DRD to run slightly slower. Notes, bestie:
    • Don't enable this option when using custom memory allocators that use VG_USERREQ__MALLOCLIKE_BLOCK and VG_USERREQ__FREELIKE_BLOCK because that would result in false positives. ๐Ÿ˜ญ
    • Don't enable this option when using reference-counted objects because that will result in false positives, even when that code has been annotated properly with ANNOTATE_HAPPENS_BEFORE and ANNOTATE_HAPPENS_AFTER. See e.g. the output of the following command for an example: valgrind --tool=drd --free-is-write=yes drd/tests/annotate_smart_pointer. it's giving โ€œtrust me, don'tโ€ ๐Ÿ‘
  • --report-signal-unlocked=<yes|no> [default: yes] โ€” Whether to report calls to pthread_cond_signal and pthread_cond_broadcast where the mutex associated with the signal through pthread_cond_wait or pthread_cond_timed_waitis is not locked at the time the signal is sent. Sending a signal without holding a lock on the associated mutex is a common programming error which can cause subtle race conditions and unpredictable behavior. There exist some uncommon synchronization patterns however where it is safe to send a signal without holding a lock on the associated mutex. mostly a red flag, occasionally not ๐Ÿšฉ
  • --segment-merging=<yes|no> [default: yes] โ€” Controls segment merging. Segment merging is an algorithm to limit memory usage of the data race detection algorithm. Disabling segment merging may improve the accuracy of the so-called 'other segments' displayed in race reports but can also trigger an out of memory error. more accuracy, more chance of the whole thing going ๐Ÿ’€
  • --segment-merging-interval=<n> [default: 10] โ€” Perform segment merging only after the specified number of new segments have been created. This is an advanced configuration option that allows one to choose whether to minimize DRD's memory usage by choosing a low value or to let DRD run faster by choosing a slightly higher value. The optimal value for this parameter depends on the program being analyzed. The default value works well for most programs. advanced little knob, very โ€œdepends on the vibesโ€ โœจ
  • --shared-threshold=<n> [default: off] โ€” Print an error message if a reader lock has been held longer than the specified time (in milliseconds). This option enables the detection of lock contention. reader lock said โ€œfive more minutesโ€ and DRD said absolutely not ๐Ÿ’…
  • --show-confl-seg=<yes|no> [default: yes] โ€” Show conflicting segments in race reports. Since this information can help to find the cause of a data race, this option is enabled by default. Disabling this option makes the output of DRD more compact. clues in the report = iconic behavior ๐Ÿ”
  • --show-stack-usage=<yes|no> [default: no] โ€” Print stack usage at thread exit time. When a program creates a large number of threads it becomes important to limit the amount of virtual memory allocated for thread stacks. This option makes it possible to observe how much stack memory has been used by each thread of the client program. Note: the DRD tool itself allocates some temporary data on the client thread stack. The space necessary for this temporary data must be allocated by the client program when it allocates stack memory, but is not included in stack usage reported by DRD. stack receipts, but with a tiny asterisk ๐Ÿ“Œ
  • --ignore-thread-creation=<yes|no> [default: no] โ€” Controls whether all activities during thread creation should be ignored. By default enabled only on Solaris. Solaris provides higher throughput, parallelism and scalability than other operating systems, at the cost of more fine-grained locking activity. This means for example that when a thread is created under glibc, just one big lock is used for all thread setup. Solaris libc uses several fine-grained locks and the creator thread resumes its activities as soon as possible, leaving for example stack and TLS setup sequence to the created thread. This situation confuses DRD as it assumes there is some false ordering in place between creator and created thread; and therefore many types of race conditions in the application would not be reported. To prevent such false ordering, this command line option is set to yes by default on Solaris. All activity (loads, stores, client requests) is therefore ignored during:
    • pthread_create() call in the creator thread
    • thread creation phase (stack and TLS setup) in the created thread
  • --trace-addr=<address> [default: none] โ€” Trace all load and store activity for the specified address. This option may be specified more than once. stare directly at one address, respectfully ๐Ÿ‘€
  • --ptrace-addr=<address> [default: none] โ€” Trace all load and store activity for the specified address and keep doing that even after the memory at that address has been freed and reallocated. not me following that address even after it moved ๐Ÿ’€
  • --trace-alloc=<yes|no> [default: no] โ€” Trace all memory allocations and deallocations. May produce a huge amount of output. โ€œhuge amount of outputโ€ is not a drill, bestie ๐Ÿ˜ญ
  • --trace-barrier=<yes|no> [default: no] โ€” Trace all barrier activity. barriers? observed. ๐Ÿงš
  • --trace-cond=<yes|no> [default: no] โ€” Trace all condition variable activity. condition variables getting the spotlight ๐Ÿ’œ
  • --trace-fork-join=<yes|no> [default: no] โ€” Trace all thread creation and all thread termination events. threads being born and leaving the chat ๐ŸŽ€
  • --trace-hb=<yes|no> [default: no] โ€” Trace execution of the ANNOTATE_HAPPENS_BEFORE(), ANNOTATE_HAPPENS_AFTER() and ANNOTATE_HAPPENS_DONE() client requests. the annotation lore is real โœจ
  • --trace-mutex=<yes|no> [default: no] โ€” Trace all mutex activity. mutex behavior: fully monitored ๐Ÿ’…
  • --trace-rwlock=<yes|no> [default: no] โ€” Trace all reader-writer lock activity. reader-writer lock drama, documented ๐Ÿ“
  • --trace-semaphore=<yes|no> [default: no] โ€” Trace all semaphore activity. semaphore slay, observed and reported ๐Ÿซถ

๐ŸŒธ MASSIF OPTIONS ๐ŸŒธ

  • --heap=<yes|no> [default: yes] โ€” bestie, do you want heap profiling? yes or no, that's the whole question ๐Ÿ’…
  • --heap-admin=<size> [default: 8] โ€” when heap profiling is on, this tells it how many admin bytes per block to budget for. heads up: this is only an estimate of the average, because the real number wobbles around. like, the allocator glibc uses on Linux needs somewhere between 4 to 15 bytes per block depending on various factors. and that same allocator also needs admin space for freed blocks, which Massif literally cannot account for. so it's giving approximation, not precision ๐Ÿซถ
  • --stacks=<yes|no> [default: no] โ€” stack profiling, yes or no? it slows Massif down greatly so it's off by default. also fyi, Massif assumes the main stack has size zero at start-up. that is not true, but doing it accurately is difficult. and starting at zero actually better indicates the size of the part of the main stack that a user program genuinely has control over โœจ

if you give at least 4 -v verbosity arguments, then massif produces a trace for each stack increase and decrease. the stack increase trace contains the IP address that increased the stack. ngl though โ€” to get a fully precise IP address, you must specify the options -px-default=unwindregs-at-mem-access and --px-file-backed=unwindregs-at-mem-access.

  • --pages-as-heap=<yes|no> [default: no] โ€” tells Massif to profile memory at the page level rather than at the malloc'd block level. "see above for details" โ€” yes diva, look up โฌ†๏ธ
  • --depth=<number> [default: 30] โ€” max depth of the allocation trees recorded for detailed snapshots. bump it up and Massif runs somewhat more slowly, eats more memory, and drops bigger output files. trade-offs, always trade-offs ๐Ÿ˜ญ
  • --alloc-fn=<name> โ€” any function you name here gets treated as though it were a heap allocation function like malloc. super useful for wrappers around malloc or new which can fill up the allocation trees with uninteresting information. you can specify this option multiple times on the command line to name multiple functions ๐Ÿ’–

โš ๏ธ ok important: the named function will only be treated this way if it's the top entry in a stack trace, or just below another function already treated this way. example time โ€” say you have a function malloc1 that wraps malloc, and malloc2 that wraps malloc1. just specifying --alloc-fn=malloc2 will have no effect. you need --alloc-fn=malloc1 as well. a little inconvenient, yes, but the reason is that checking for allocation functions is slow, and it saves a lot of time if Massif can stop looking through the stack trace entries as soon as it finds one that doesn't match, rather than having to continue through all the entries. efficiency queen ๐Ÿ‘‘

also: C++ names are demangled. and overloaded C++ names must be written in full. single quotes may be necessary to stop the shell from breaking them up. like this:

--alloc-fn='operator new(unsigned, std::nothrow_t const&)'

arguments of type size_t need to be replaced with unsigned long on 64bit platforms and unsigned on 32bit platforms. ik, annoying.

--alloc-fn will work with inline functions. inline function names are not mangled, which means you only need to provide the function name and not the argument list ๐ŸŽ€

--alloc-fn does not support wildcards. sorry babes.

  • --ignore-fn=<name> โ€” any direct heap allocation (i.e. a call to malloc, new, etc, or a call to a function named by an --alloc-fn option) that occurs in a function specified by this option will be ignored. mostly useful for testing purposes. can be specified multiple times on the command line to name multiple functions โœจ

any realloc of an ignored block will also be ignored, even if the realloc call does not occur in an ignored function. this avoids the possibility of negative heap sizes if ignored blocks are shrunk with realloc. smart, honestly ๐Ÿง 

the rules for writing C++ function names are the same as for --alloc-fn above.

  • --threshold=<m.n> [default: 1.0] โ€” the significance threshold for heap allocations, as a percentage of total memory size. allocation tree entries that account for less than this get aggregated. note that you should specify this in tandem with ms_print's option of the same name โ€” they're a matching set, don't split them up ๐Ÿ’…
  • --peak-inaccuracy=<m.n> [default: 1.0] โ€” Massif doesn't necessarily record the actual global memory allocation peak; by default it only records a peak when the global memory allocation size exceeds the previous peak by at least 1.0%. why? because there can be many local allocation peaks along the way, and doing a detailed snapshot for every single one would be expensive and wasteful, since all but one of them get discarded later anyway. you can change this inaccuracy (even down to 0.0%) via this option, but heads up โ€” Massif will run drastically slower as the number approaches zero ๐Ÿ˜ญ๐Ÿ”ฅ
  • --time-unit=<i|ms|B> [default: i] โ€” the time unit used for profiling. three possibilities, bestie:
    • instructions executed (i) โ€” good for most cases ๐Ÿ‘‘
    • real (wallclock) time (ms, i.e. milliseconds) โ€” sometimes useful
    • bytes allocated/deallocated on the heap and/or stack (B) โ€” useful for very short-run programs and for testing purposes, because it's the most reproducible across different machines โœจ
  • --detailed-freq=<n> [default: 10] โ€” frequency of detailed snapshots. with --detailed-freq=1, every snapshot is detailed. every. single. one. ๐Ÿ’€
  • --max-snapshots=<n> [default: 100] โ€” the maximum number of snapshots recorded. if set to N, then for all programs except very short-running ones, the final number of snapshots will be between N/2 and N ๐ŸŽ€
  • --massif-out-file=<file> [default: massif.out.%p] โ€” write the profile data to file rather than to the default output file, massif.out.<pid>. the %p and %q format specifiers can be used to embed the process ID and/or the contents of an environment variable in the name, as is the case for the core option --log-file ๐Ÿฆ‹

๐Ÿฆ‹ BBV OPTIONS ๐Ÿฆ‹

  • --bb-out-file=<name> [default: bb.out.%p] โ€” selects the name of the basic block vector file. the %p and %q format specifiers can be used to embed the process ID and/or the contents of an environment variable in the name, as is the case for the core option --log-file โœจ
  • --pc-out-file=<name> [default: pc.out.%p] โ€” selects the name of the PC file. this file holds program counter addresses and function name info for the various basic blocks. you can use it together with the basic block vector file to fast-forward via function names instead of just instruction counts. the %p and %q format specifiers can be used to embed the process ID and/or the contents of an environment variable in the name, as is the case for the core option --log-file ๐Ÿ’–
  • --interval-size=<number> [default: 100000000] โ€” selects the size of the interval to use. default is 100 million instructions, which is a commonly used value. other sizes can be used; smaller intervals can help programs with finer-grained phases. however, smaller interval size can lead to accuracy issues due to warm-up effects โ€” when fast-forwarding, the various architectural features will be un-initialized, and it'll take some number of instructions before they "warm up" to the state a full simulation would be at without the fast-forwarding. large interval sizes tend to mitigate this ๐Ÿซถ
  • --instr-count-only [default: no] โ€” tells the tool to only display instruction count totals, and to not generate the actual basic block vector file. useful for debugging, and for gathering instruction count info without generating the large basic block vector files ๐Ÿ”ฅ

๐ŸŽ€ LACKEY OPTIONS ๐ŸŽ€

  • --basic-counts=<no|yes> [default: yes] โ€” when enabled, Lackey prints the following statistics and information about the execution of the client program:
    1. the number of calls to the function specified by the --fnname option (the default is main). if the program has had its symbols stripped, the count will always be zero ๐Ÿ˜ฌ
    2. the number of conditional branches encountered and the number and proportion of those taken.
    3. the number of superblocks entered and completed by the program. note that due to optimisations done by the JIT, this is not at all an accurate value ๐Ÿ’€
    4. the number of guest (x86, amd64, ppc, etc.) instructions and IR statements executed. IR is Valgrind's RISC-like intermediate representation via which all instrumentation is done โœจ
    5. ratios between some of these counts.
    6. the exit code of the client program.
  • --detailed-counts=<no|yes> [default: no] โ€” when enabled, Lackey prints a table containing counts of loads, stores and ALU operations, differentiated by their IR types. the IR types are identified by their IR name ("I1", "I8", ... "I128", "F32", "F64", and "V128") ๐ŸŽ€
  • --trace-mem=<no|yes> [default: no] โ€” when enabled, Lackey prints the size and address of almost every memory access made by the program. see the comments at the top of the file lackey/lk_main.c for details about the output format, how it works, and inaccuracies in the address trace. โš ๏ธ note that this option produces immense amounts of output. like, bring a snack ๐Ÿ“
  • --trace-superblocks=<no|yes> [default: no] โ€” when enabled, Lackey prints out the address of every superblock (a single entry, multiple exit, linear chunk of code) executed by the program. primarily of interest to Valgrind developers ๐Ÿ‘‘ see the comments at the top of the file lackey/lk_main.c for details about the output format. โš ๏ธ note that this option produces large amounts of output.
  • --fnname=<name> [default: main] โ€” changes the function for which calls are counted when --basic-counts=yes is specified ๐Ÿ’…

๐Ÿ’œ DEBUGINFOD ๐Ÿ’œ

Valgrind supports the downloading of debuginfo files via debuginfod, an HTTP server for distributing ELF/DWARF debugging information. when a debuginfo file can't be found locally, Valgrind is able to query debuginfod servers for the file using the file's build-id โœจ

in order to use this feature, debuginfod-find must be installed and the $DEBUGINFOD_URLS environment variable must contain space-separated URLs of debuginfod servers ๐Ÿฆ‹

heads up though โ€” Valgrind does not support debuginfod-find verbose output, which is normally enabled with $DEBUGINFOD_PROGRESS and $DEBUGINFOD_VERBOSE. those environment variables will be ignored ๐Ÿ™ˆ and this feature is supported on Linux only.

for more information regarding debuginfod, see Elfutils Debuginfod[1] ๐Ÿ’–

๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

okay bestie, when you're done living your Valgrind main-character era, here's the whole iconic reading list โ€” every single one, no skips:


โœ๏ธ AUTHOR โœ๏ธ

the lore: see the AUTHORS file in the valgrind distribution for a comprehensive list of authors. slay, credit where credit is due ๐Ÿ’–

This manpage was written by Andres Roldan <aroldan@debian.org> and the Valgrind developers. iconic collaboration, honestly ๐Ÿซถ


๐Ÿ—’๏ธ NOTES ๐Ÿ—’๏ธ

  1. Elfutils Debuginfod โ€” https://sourceware.org/elfutils/Debuginfod.html
  2. Debugging your program using Valgrind's gdbserver and GDB โ€” http://www.valgrind.org/docs/manual/manual-core-adv.html#manual-core-adv.gdbserver
  3. vgdb โ€” http://www.valgrind.org/docs/manual/manual-core-adv.html#manual-core-adv.vgdb
  4. Valgrind monitor commands โ€” http://www.valgrind.org/docs/manual/manual-core-adv.html#manual-core-adv.valgrind-monitor-commands
  5. The Commentary โ€” http://www.valgrind.org/docs/manual/manual-core.html#manual-core.comment
  6. Scheduling and Multi-Thread Performance โ€” http://www.valgrind.org/docs/manual/manual-core.html#manual-core.pthreads_perf_sched
  7. Cachegrind: a cache and branch-prediction profiler โ€” http://www.valgrind.org/docs/manual/cg-manual.html
  8. Execution Trees โ€” http://www.valgrind.org/docs/manual/manual-core.html#manual-core.xtree

and that's the whole iconic manual, bestie โ€” this edition is from Release 3.27.1, dated 06/23/2026, and it's the VALGRIND(1) page. periodt. ๐Ÿ’…โœจ๐Ÿ‘‘

๐Ÿ“ฆ where this page comes from