Memcheck a memory error detector

Official Home Page for valgrind, a suite of tools for debugging and profiling. Automatically detect memory management and threading bugs, and perform detailed profiling. The current stable version is valgrind-3.20.0.

4. Memcheck: a memory error detector

To use this tool, you may specify --tool=memcheck
on the Valgrind command line. You don’t have to, though, since Memcheck
is the default tool.

4.1. Overview

Memcheck is a memory error detector. It can detect the following
problems that are common in C and C++ programs.

  • Accessing memory you shouldn’t, e.g. overrunning and underrunning
    heap blocks, overrunning the top of the stack, and accessing memory after
    it has been freed.

  • Using undefined values, i.e. values that have not been initialised,
    or that have been derived from other undefined values.

  • Incorrect freeing of heap memory, such as double-freeing heap
    blocks, or mismatched use of
    malloc/new/new[]
    versus
    free/delete/delete[]

  • Overlapping src and
    dst pointers in
    memcpy and related
    functions.

  • Passing a fishy (presumably negative) value to the
    size parameter of a memory
    allocation function.

  • Memory leaks.

Problems like these can be difficult to find by other means,
often remaining undetected for long periods, then causing occasional,
difficult-to-diagnose crashes.

Memcheck also provides Execution Trees memory
profiling using the command line
option --xtree-memory and the monitor command
xtmemory.

4.2. Explanation of error messages from Memcheck

Memcheck issues a range of error messages. This section presents a
quick summary of what error messages mean. The precise behaviour of the
error-checking machinery is described in Details of Memcheck’s checking machinery.

4.2.1. Illegal read / Illegal write errors

For example:

Invalid read of size 4
   at 0x40F6BBCC: (within /usr/lib/libpng.so.2.1.0.9)
   by 0x40F6B804: (within /usr/lib/libpng.so.2.1.0.9)
   by 0x40B07FF4: read_png_image(QImageIO *) (kernel/qpngio.cpp:326)
   by 0x40AC751B: QImageIO::read() (kernel/qimage.cpp:3621)
 Address 0xBFFFF0E0 is not stack'd, malloc'd or free'd

This happens when your program reads or writes memory at a place
which Memcheck reckons it shouldn’t. In this example, the program did a
4-byte read at address 0xBFFFF0E0, somewhere within the system-supplied
library libpng.so.2.1.0.9, which was called from somewhere else in the
same library, called from line 326 of qpngio.cpp,
and so on.

Memcheck tries to establish what the illegal address might relate
to, since that’s often useful. So, if it points into a block of memory
which has already been freed, you’ll be informed of this, and also where
the block was freed. Likewise, if it should turn out to be just off
the end of a heap block, a common result of off-by-one-errors in
array subscripting, you’ll be informed of this fact, and also where the
block was allocated. If you use the --read-var-info option
Memcheck will run more slowly
but may give a more detailed description of any illegal address.

In this example, Memcheck can’t identify the address. Actually
the address is on the stack, but, for some reason, this is not a valid
stack address — it is below the stack pointer and that isn’t allowed.
In this particular case it’s probably caused by GCC generating invalid
code, a known bug in some ancient versions of GCC.

Note that Memcheck only tells you that your program is about to
access memory at an illegal address. It can’t stop the access from
happening. So, if your program makes an access which normally would
result in a segmentation fault, you program will still suffer the same
fate — but you will get a message from Memcheck immediately prior to
this. In this particular example, reading junk on the stack is
non-fatal, and the program stays alive.

4.2.2. Use of uninitialised values

For example:

Conditional jump or move depends on uninitialised value(s)
   at 0x402DFA94: _IO_vfprintf (_itoa.h:49)
   by 0x402E8476: _IO_printf (printf.c:36)
   by 0x8048472: main (tests/manuel1.c:8)

An uninitialised-value use error is reported when your program
uses a value which hasn’t been initialised — in other words, is
undefined. Here, the undefined value is used somewhere inside the
printf machinery of the C library. This error was
reported when running the following small program:

int main()
{
  int x;
  printf ("x = %dn", x);
}

It is important to understand that your program can copy around
junk (uninitialised) data as much as it likes. Memcheck observes this
and keeps track of the data, but does not complain. A complaint is
issued only when your program attempts to make use of uninitialised
data in a way that might affect your program’s externally-visible behaviour.
In this example, x is uninitialised. Memcheck observes
the value being passed to _IO_printf and thence to
_IO_vfprintf, but makes no comment. However,
_IO_vfprintf has to examine the value of
x so it can turn it into the corresponding ASCII string,
and it is at this point that Memcheck complains.

Sources of uninitialised data tend to be:

  • Local variables in procedures which have not been initialised,
    as in the example above.

  • The contents of heap blocks (allocated with
    malloc, new, or a similar
    function) before you (or a constructor) write something there.

To see information on the sources of uninitialised data in your
program, use the --track-origins=yes option. This
makes Memcheck run more slowly, but can make it much easier to track down
the root causes of uninitialised value errors.

4.2.3. Use of uninitialised or unaddressable values in system
calls

Memcheck checks all parameters to system calls:

  • It checks all the direct parameters themselves, whether they are
    initialised.

  • Also, if a system call needs to read from a buffer provided by
    your program, Memcheck checks that the entire buffer is addressable
    and its contents are initialised.

  • Also, if the system call needs to write to a user-supplied
    buffer, Memcheck checks that the buffer is addressable.

After the system call, Memcheck updates its tracked information to
precisely reflect any changes in memory state caused by the system
call.

Here’s an example of two system calls with invalid parameters:

  #include <stdlib.h>
  #include <unistd.h>
  int main( void )
  {
    char* arr  = malloc(10);
    int*  arr2 = malloc(sizeof(int));
    write( 1 /* stdout */, arr, 10 );
    exit(arr2[0]);
  }

You get these complaints …

  Syscall param write(buf) points to uninitialised byte(s)
     at 0x25A48723: __write_nocancel (in /lib/tls/libc-2.3.3.so)
     by 0x259AFAD3: __libc_start_main (in /lib/tls/libc-2.3.3.so)
     by 0x8048348: (within /auto/homes/njn25/grind/head4/a.out)
   Address 0x25AB8028 is 0 bytes inside a block of size 10 alloc'd
     at 0x259852B0: malloc (vg_replace_malloc.c:130)
     by 0x80483F1: main (a.c:5)

  Syscall param exit(error_code) contains uninitialised byte(s)
     at 0x25A21B44: __GI__exit (in /lib/tls/libc-2.3.3.so)
     by 0x8048426: main (a.c:8)

… because the program has (a) written uninitialised junk
from the heap block to the standard output, and (b) passed an
uninitialised value to exit. Note that the first
error refers to the memory pointed to by
buf (not
buf itself), but the second error
refers directly to exit‘s argument
arr2[0].

4.2.4. Illegal frees

For example:

Invalid free()
   at 0x4004FFDF: free (vg_clientmalloc.c:577)
   by 0x80484C7: main (tests/doublefree.c:10)
 Address 0x3807F7B4 is 0 bytes inside a block of size 177 free'd
   at 0x4004FFDF: free (vg_clientmalloc.c:577)
   by 0x80484C7: main (tests/doublefree.c:10)

Memcheck keeps track of the blocks allocated by your program
with malloc/new,
so it can know exactly whether or not the argument to
free/delete is
legitimate or not. Here, this test program has freed the same block
twice. As with the illegal read/write errors, Memcheck attempts to
make sense of the address freed. If, as here, the address is one
which has previously been freed, you wil be told that — making
duplicate frees of the same block easy to spot. You will also get this
message if you try to free a pointer that doesn’t point to the start of a
heap block.

4.2.5. When a heap block is freed with an inappropriate deallocation
function

In the following example, a block allocated with
new[] has wrongly been deallocated with
free:

Mismatched free() / delete / delete []
   at 0x40043249: free (vg_clientfuncs.c:171)
   by 0x4102BB4E: QGArray::~QGArray(void) (tools/qgarray.cpp:149)
   by 0x4C261C41: PptDoc::~PptDoc(void) (include/qmemarray.h:60)
   by 0x4C261F0E: PptXml::~PptXml(void) (pptxml.cc:44)
 Address 0x4BB292A8 is 0 bytes inside a block of size 64 alloc'd
   at 0x4004318C: operator new[](unsigned int) (vg_clientfuncs.c:152)
   by 0x4C21BC15: KLaola::readSBStream(int) const (klaola.cc:314)
   by 0x4C21C155: KLaola::stream(KLaola::OLENode const *) (klaola.cc:416)
   by 0x4C21788F: OLEFilter::convert(QCString const &) (olefilter.cc:272)

In C++ it’s important to deallocate memory in a
way compatible with how it was allocated. The deal is:

  • If allocated with
    malloc,
    calloc,
    realloc,
    valloc or
    memalign, you must
    deallocate with free.

  • If allocated with new, you must deallocate
    with delete.

  • If allocated with new[], you must
    deallocate with delete[].

The worst thing is that on Linux apparently it doesn’t matter if
you do mix these up, but the same program may then crash on a
different platform, Solaris for example. So it’s best to fix it
properly. According to the KDE folks «it’s amazing how many C++
programmers don’t know this».

The reason behind the requirement is as follows. In some C++
implementations, delete[] must be used for
objects allocated by new[] because the compiler
stores the size of the array and the pointer-to-member to the
destructor of the array’s content just before the pointer actually
returned. delete doesn’t account for this and will get
confused, possibly corrupting the heap.

4.2.6. Overlapping source and destination blocks

The following C library functions copy some data from one
memory block to another (or something similar):
memcpy,
strcpy,
strncpy,
strcat,
strncat.
The blocks pointed to by their src and
dst pointers aren’t allowed to overlap.
The POSIX standards have wording along the lines «If copying takes place
between objects that overlap, the behavior is undefined.» Therefore,
Memcheck checks for this.

For example:

==27492== Source and destination overlap in memcpy(0xbffff294, 0xbffff280, 21)
==27492==    at 0x40026CDC: memcpy (mc_replace_strmem.c:71)
==27492==    by 0x804865A: main (overlap.c:40)

You don’t want the two blocks to overlap because one of them could
get partially overwritten by the copying.

You might think that Memcheck is being overly pedantic reporting
this in the case where dst is less than
src. For example, the obvious way to
implement memcpy is by copying from the first
byte to the last. However, the optimisation guides of some
architectures recommend copying from the last byte down to the first.
Also, some implementations of memcpy zero
dst before copying, because zeroing the
destination’s cache line(s) can improve performance.

The moral of the story is: if you want to write truly portable
code, don’t make any assumptions about the language
implementation.

4.2.7. Fishy argument values

All memory allocation functions take an argument specifying the
size of the memory block that should be allocated. Clearly, the requested
size should be a non-negative value and is typically not excessively large.
For instance, it is extremely unlikly that the size of an allocation
request exceeds 2**63 bytes on a 64-bit machine. It is much more likely that
such a value is the result of an erroneous size calculation and is in effect
a negative value (that just happens to appear excessively large because
the bit pattern is interpreted as an unsigned integer).
Such a value is called a «fishy value».

The size argument of the following allocation functions
is checked for being fishy:
malloc,
calloc,
realloc,
memalign,
new,
new [].
__builtin_new,
__builtin_vec_new,
For calloc both arguments are being checked.

For example:

==32233== Argument 'size' of function malloc has a fishy (possibly negative) value: -3
==32233==    at 0x4C2CFA7: malloc (vg_replace_malloc.c:298)
==32233==    by 0x400555: foo (fishy.c:15)
==32233==    by 0x400583: main (fishy.c:23)

In earlier Valgrind versions those values were being referred to
as «silly arguments» and no back-trace was included.

4.2.8. Memory leak detection

Memcheck keeps track of all heap blocks issued in response to
calls to
malloc/new et al.
So when the program exits, it knows which blocks have not been freed.

If --leak-check is set appropriately, for each
remaining block, Memcheck determines if the block is reachable from pointers
within the root-set. The root-set consists of (a) general purpose registers
of all threads, and (b) initialised, aligned, pointer-sized data words in
accessible client memory, including stacks.

There are two ways a block can be reached. The first is with a
«start-pointer», i.e. a pointer to the start of the block. The second is with
an «interior-pointer», i.e. a pointer to the middle of the block. There are
several ways we know of that an interior-pointer can occur:

  • The pointer might have originally been a start-pointer and have been
    moved along deliberately (or not deliberately) by the program. In
    particular, this can happen if your program uses tagged pointers, i.e.
    if it uses the bottom one, two or three bits of a pointer, which are
    normally always zero due to alignment, in order to store extra
    information.

  • It might be a random junk value in memory, entirely unrelated, just
    a coincidence.

  • It might be a pointer to the inner char array of a C++
    std::string. For example, some
    compilers add 3 words at the beginning of the std::string to
    store the length, the capacity and a reference count before the
    memory containing the array of characters. They return a pointer
    just after these 3 words, pointing at the char array.

  • Some code might allocate a block of memory, and use the first 8
    bytes to store (block size — 8) as a 64bit number.
    sqlite3MemMalloc does this.

  • It might be a pointer to an array of C++ objects (which possess
    destructors) allocated with new[]. In
    this case, some compilers store a «magic cookie» containing the array
    length at the start of the allocated block, and return a pointer to just
    past that magic cookie, i.e. an interior-pointer.
    See this
    page for more information.

  • It might be a pointer to an inner part of a C++ object using
    multiple inheritance.

You can optionally activate heuristics to use during the leak
search to detect the interior pointers corresponding to
the stdstring,
length64,
newarray
and multipleinheritance cases. If the
heuristic detects that an interior pointer corresponds to such a case,
the block will be considered as reachable by the interior
pointer. In other words, the interior pointer will be treated
as if it were a start pointer.

With that in mind, consider the nine possible cases described by the
following figure.

     Pointer chain            AAA Leak Case   BBB Leak Case
     -------------            -------------   -------------
(1)  RRR ------------> BBB                    DR
(2)  RRR ---> AAA ---> BBB    DR              IR
(3)  RRR               BBB                    DL
(4)  RRR      AAA ---> BBB    DL              IL
(5)  RRR ------?-----> BBB                    (y)DR, (n)DL
(6)  RRR ---> AAA -?-> BBB    DR              (y)IR, (n)DL
(7)  RRR -?-> AAA ---> BBB    (y)DR, (n)DL    (y)IR, (n)IL
(8)  RRR -?-> AAA -?-> BBB    (y)DR, (n)DL    (y,y)IR, (n,y)IL, (_,n)DL
(9)  RRR      AAA -?-> BBB    DL              (y)IL, (n)DL

Pointer chain legend:
- RRR: a root set node or DR block
- AAA, BBB: heap blocks
- --->: a start-pointer
- -?->: an interior-pointer

Leak Case legend:
- DR: Directly reachable
- IR: Indirectly reachable
- DL: Directly lost
- IL: Indirectly lost
- (y)XY: it's XY if the interior-pointer is a real pointer
- (n)XY: it's XY if the interior-pointer is not a real pointer
- (_)XY: it's XY in either case

Every possible case can be reduced to one of the above nine. Memcheck
merges some of these cases in its output, resulting in the following four
leak kinds.

  • «Still reachable». This covers cases 1 and 2 (for the BBB blocks)
    above. A start-pointer or chain of start-pointers to the block is
    found. Since the block is still pointed at, the programmer could, at
    least in principle, have freed it before program exit. «Still reachable»
    blocks are very common and arguably not a problem. So, by default,
    Memcheck won’t report such blocks individually.

  • «Definitely lost». This covers case 3 (for the BBB blocks) above.
    This means that no pointer to the block can be found. The block is
    classified as «lost», because the programmer could not possibly have
    freed it at program exit, since no pointer to it exists. This is likely
    a symptom of having lost the pointer at some earlier point in the
    program. Such cases should be fixed by the programmer.

  • «Indirectly lost». This covers cases 4 and 9 (for the BBB blocks)
    above. This means that the block is lost, not because there are no
    pointers to it, but rather because all the blocks that point to it are
    themselves lost. For example, if you have a binary tree and the root
    node is lost, all its children nodes will be indirectly lost. Because
    the problem will disappear if the definitely lost block that caused the
    indirect leak is fixed, Memcheck won’t report such blocks individually
    by default.

  • «Possibly lost». This covers cases 5—8 (for the BBB blocks)
    above. This means that a chain of one or more pointers to the block has
    been found, but at least one of the pointers is an interior-pointer.
    This could just be a random value in memory that happens to point into a
    block, and so you shouldn’t consider this ok unless you know you have
    interior-pointers.

(Note: This mapping of the nine possible cases onto four leak kinds is
not necessarily the best way that leaks could be reported; in particular,
interior-pointers are treated inconsistently. It is possible the
categorisation may be improved in the future.)

Furthermore, if suppressions exists for a block, it will be reported
as «suppressed» no matter what which of the above four kinds it belongs
to.

The following is an example leak summary.

LEAK SUMMARY:
   definitely lost: 48 bytes in 3 blocks.
   indirectly lost: 32 bytes in 2 blocks.
     possibly lost: 96 bytes in 6 blocks.
   still reachable: 64 bytes in 4 blocks.
        suppressed: 0 bytes in 0 blocks.

If heuristics have been used to consider some blocks as
reachable, the leak summary details the heuristically reachable subset
of ‘still reachable:’ per heuristic. In the below example, of the 95
bytes still reachable, 87 bytes (56+7+8+16) have been considered
heuristically reachable.

LEAK SUMMARY:
   definitely lost: 4 bytes in 1 blocks
   indirectly lost: 0 bytes in 0 blocks
     possibly lost: 0 bytes in 0 blocks
   still reachable: 95 bytes in 6 blocks
                      of which reachable via heuristic:
                        stdstring          : 56 bytes in 2 blocks
                        length64           : 16 bytes in 1 blocks
                        newarray           : 7 bytes in 1 blocks
                        multipleinheritance: 8 bytes in 1 blocks
        suppressed: 0 bytes in 0 blocks

If --leak-check=full is specified,
Memcheck will give details for each definitely lost or possibly lost block,
including where it was allocated. (Actually, it merges results for all
blocks that have the same leak kind and sufficiently similar stack traces
into a single «loss record». The
--leak-resolution lets you control the
meaning of «sufficiently similar».) It cannot tell you when or how or why
the pointer to a leaked block was lost; you have to work that out for
yourself. In general, you should attempt to ensure your programs do not
have any definitely lost or possibly lost blocks at exit.

For example:

8 bytes in 1 blocks are definitely lost in loss record 1 of 14
   at 0x........: malloc (vg_replace_malloc.c:...)
   by 0x........: mk (leak-tree.c:11)
   by 0x........: main (leak-tree.c:39)

88 (8 direct, 80 indirect) bytes in 1 blocks are definitely lost in loss record 13 of 14
   at 0x........: malloc (vg_replace_malloc.c:...)
   by 0x........: mk (leak-tree.c:11)
   by 0x........: main (leak-tree.c:25)

The first message describes a simple case of a single 8 byte block
that has been definitely lost. The second case mentions another 8 byte
block that has been definitely lost; the difference is that a further 80
bytes in other blocks are indirectly lost because of this lost block.
The loss records are not presented in any notable order, so the loss record
numbers aren’t particularly meaningful. The loss record numbers can be used
in the Valgrind gdbserver to list the addresses of the leaked blocks and/or give
more details about how a block is still reachable.

The option --show-leak-kinds=<set>
controls the set of leak kinds to show
when --leak-check=full is specified.

The <set> of leak kinds is specified
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).

  • none for the empty set.

The default value for the leak kinds to show is
--show-leak-kinds=definite,possible.

To also show the reachable and indirectly lost blocks in
addition to the definitely and possibly lost blocks, you can
use --show-leak-kinds=all. To only show the
reachable and indirectly lost blocks, use
--show-leak-kinds=indirect,reachable. The reachable
and indirectly lost blocks will then be presented as shown in
the following two examples.

64 bytes in 4 blocks are still reachable in loss record 2 of 4
   at 0x........: malloc (vg_replace_malloc.c:177)
   by 0x........: mk (leak-cases.c:52)
   by 0x........: main (leak-cases.c:74)

32 bytes in 2 blocks are indirectly lost in loss record 1 of 4
   at 0x........: malloc (vg_replace_malloc.c:177)
   by 0x........: mk (leak-cases.c:52)
   by 0x........: main (leak-cases.c:80)

Because there are different kinds of leaks with different
severities, an interesting question is: which leaks should be
counted as true «errors» and which should not?

The answer to this question affects the numbers printed in
the ERROR SUMMARY line, and also the
effect of the --error-exitcode option. First, a leak
is only counted as a true «error»
if --leak-check=full is specified. Then, the
option --errors-for-leak-kinds=<set> controls
the set of leak kinds to consider as errors. The default value
is --errors-for-leak-kinds=definite,possible

4.3. Memcheck Command-Line 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.

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.


--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.

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.


--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


--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.


--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.


--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 visualise.
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.

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.
AddrCheck (removed in Valgrind 3.1.0) functioned like Memcheck with
--undef-value-errors=no.


--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.

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.

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.

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.


--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.


--expensive-definedness-checks=<no|auto|yes> [default: auto]

Controls whether Memcheck should employ more precise but also
more expensive (time consuming) instrumentation when checking the
definedness of certain values. In particular, this affects the
instrumentation of integer adds, subtracts and equality
comparisons.

Selecting --expensive-definedness-checks=yes
causes Memcheck to use the most accurate analysis possible. This
minimises false error rates but can cause up to 30% performance
degradation.

Selecting --expensive-definedness-checks=no
causes Memcheck to use the cheapest instrumentation possible. This
maximises performance but will normally give an unusably high false
error rate.

The default
setting, --expensive-definedness-checks=auto, is
strongly recommended. This causes Memcheck to use the minimum of
expensive instrumentation needed to achieve the same false error
rate as --expensive-definedness-checks=yes. It
also enables an instrumentation-time analysis pass which 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 allocation
and the deallocation stack traces for the block are stored.
Hence 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.


--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 is 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
have been freed.

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. 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.


--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.


--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.

4.4. Writing suppression files

The basic suppression format is described in
Suppressing errors.

The suppression-type (second) line should have the form:

Memcheck:suppression_type

The Memcheck suppression types are as follows:

  • Value1,
    Value2,
    Value4,
    Value8,
    Value16,
    meaning an uninitialised-value error when
    using a value of 1, 2, 4, 8 or 16 bytes.

  • Cond (or its old
    name, Value0), meaning use
    of an uninitialised CPU condition code.

  • Addr1,
    Addr2,
    Addr4,
    Addr8,
    Addr16,
    meaning an invalid address during a
    memory access of 1, 2, 4, 8 or 16 bytes respectively.

  • Jump, meaning an
    jump to an unaddressable location error.

  • Param, meaning an
    invalid system call parameter error.

  • Free, meaning an
    invalid or mismatching free.

  • Overlap, meaning a
    src /
    dst overlap in
    memcpy or a similar function.

  • Leak, meaning
    a memory leak.

Param errors have a mandatory extra
information line at this point, which is the name of the offending
system call parameter.

Leak errors have an optional
extra information line, with the following format:

match-leak-kinds:<set>

where <set> specifies which
leak kinds are matched by this suppression entry.
<set> is specified in the
same way as with the option --show-leak-kinds, that is,
one of the following:

  • a comma separated list of one or more of
    definite indirect possible reachable.

  • all to specify the complete set
    (all leak kinds).

  • none for the empty set.

If this optional extra line is not present, the suppression
entry will match all leak kinds.

Be aware that leak suppressions that are created using
--gen-suppressions will contain this optional extra
line, and therefore may match fewer leaks than you expect. You may
want to remove the line before using the generated
suppressions.

The other Memcheck error kinds do not have extra lines.

If you give the -v option, Valgrind will print
the list of used suppressions at the end of execution.
For a leak suppression, this output gives the number of different
loss records that match the suppression, and the number of bytes
and blocks suppressed by the suppression.
If the run contains multiple leak checks, the number of bytes and blocks
are reset to zero before each new leak check. Note that the number of different
loss records is not reset to zero.

In the example below, in the last leak search, 7 blocks and 96 bytes have
been suppressed by a suppression with the name
some_leak_suppression:

--21041-- used_suppression:     10 some_other_leak_suppression s.supp:14 suppressed: 12,400 bytes in 1 blocks
--21041-- used_suppression:     39 some_leak_suppression s.supp:2 suppressed: 96 bytes in 7 blocks

For ValueN and AddrN
errors, the first line of the calling context is either the name of
the function in which the error occurred, or, failing that, the full
path of the .so file or executable containing the
error location. For Free errors, the first line is
the name of the function doing the freeing (eg,
free, __builtin_vec_delete,
etc). For Overlap errors, the first line is the name of the
function with the overlapping arguments (eg.
memcpy, strcpy, etc).

The last part of any suppression specifies the rest of the
calling context that needs to be matched.

4.5. Details of Memcheck’s checking machinery

Read this section if you want to know, in detail, exactly
what and how Memcheck is checking.

4.5.1. Valid-value (V) bits

It is simplest to think of Memcheck implementing a synthetic CPU
which is identical to a real CPU, except for one crucial detail. Every
bit (literally) of data processed, stored and handled by the real CPU
has, in the synthetic CPU, an associated «valid-value» bit, which says
whether or not the accompanying bit has a legitimate value. In the
discussions which follow, this bit is referred to as the V (valid-value)
bit.

Each byte in the system therefore has a 8 V bits which follow it
wherever it goes. For example, when the CPU loads a word-size item (4
bytes) from memory, it also loads the corresponding 32 V bits from a
bitmap which stores the V bits for the process’ entire address space.
If the CPU should later write the whole or some part of that value to
memory at a different address, the relevant V bits will be stored back
in the V-bit bitmap.

In short, each bit in the system has (conceptually) an associated V
bit, which follows it around everywhere, even inside the CPU. Yes, all the
CPU’s registers (integer, floating point, vector and condition registers)
have their own V bit vectors. For this to work, Memcheck uses a great deal
of compression to represent the V bits compactly.

Copying values around does not cause Memcheck to check for, or
report on, errors. However, when a value is used in a way which might
conceivably affect your program’s externally-visible behaviour,
the associated V bits are immediately checked. If any of these indicate
that the value is undefined (even partially), an error is reported.

Here’s an (admittedly nonsensical) example:

int i, j;
int a[10], b[10];
for ( i = 0; i < 10; i++ ) {
  j = a[i];
  b[i] = j;
}

Memcheck emits no complaints about this, since it merely copies
uninitialised values from a[] into
b[], and doesn’t use them in a way which could
affect the behaviour of the program. However, if
the loop is changed to:

for ( i = 0; i < 10; i++ ) {
  j += a[i];
}
if ( j == 77 ) 
  printf("hello theren");

then Memcheck will complain, at the
if, that the condition depends on
uninitialised values. Note that it doesn’t complain
at the j += a[i];, since at that point the
undefinedness is not «observable». It’s only when a decision has to be
made as to whether or not to do the printf — an
observable action of your program — that Memcheck complains.

Most low level operations, such as adds, cause Memcheck to use the
V bits for the operands to calculate the V bits for the result. Even if
the result is partially or wholly undefined, it does not
complain.

Checks on definedness only occur in three places: when a value is
used to generate a memory address, when control flow decision needs to
be made, and when a system call is detected, Memcheck checks definedness
of parameters as required.

If a check should detect undefinedness, an error message is
issued. The resulting value is subsequently regarded as well-defined.
To do otherwise would give long chains of error messages. In other
words, once Memcheck reports an undefined value error, it tries to
avoid reporting further errors derived from that same undefined
value.

This sounds overcomplicated. Why not just check all reads from
memory, and complain if an undefined value is loaded into a CPU
register? Well, that doesn’t work well, because perfectly legitimate C
programs routinely copy uninitialised values around in memory, and we
don’t want endless complaints about that. Here’s the canonical example.
Consider a struct like this:

struct S { int x; char c; };
struct S s1, s2;
s1.x = 42;
s1.c = 'z';
s2 = s1;

The question to ask is: how large is struct S,
in bytes? An int is 4 bytes and a
char one byte, so perhaps a struct
S
occupies 5 bytes? Wrong. All non-toy compilers we know
of will round the size of struct S up to a whole
number of words, in this case 8 bytes. Not doing this forces compilers
to generate truly appalling code for accessing arrays of
struct S‘s on some architectures.

So s1 occupies 8 bytes, yet only 5 of them will
be initialised. For the assignment s2 = s1, GCC
generates code to copy all 8 bytes wholesale into s2
without regard for their meaning. If Memcheck simply checked values as
they came out of memory, it would yelp every time a structure assignment
like this happened. So the more complicated behaviour described above
is necessary. This allows GCC to copy
s1 into s2 any way it likes, and a
warning will only be emitted if the uninitialised values are later
used.

As explained above, Memcheck maintains 8 V bits for each byte in your
process, including for bytes that are in shared memory. However, the same piece
of shared memory can be mapped multiple times, by several processes or even by
the same process (for example, if the process wants a read-only and a read-write
mapping of the same page). For such multiple mappings, Memcheck tracks the V
bits for each mapping independently. This can lead to false positive errors, as
the shared memory can be initialised via a first mapping, and accessed via
another mapping. The access via this other mapping will have its own V bits,
which have not been changed when the memory was initialised via the first
mapping. The bypass for these false positives is to use Memcheck’s client
requests VALGRIND_MAKE_MEM_DEFINED and
VALGRIND_MAKE_MEM_UNDEFINED to inform
Memcheck about what your program does (or what another process does)
to these shared memory mappings.

4.5.2. Valid-address (A) bits

Notice that the previous subsection describes how the validity of
values is established and maintained without having to say whether the
program does or does not have the right to access any particular memory
location. We now consider the latter question.

As described above, every bit in memory or in the CPU has an
associated valid-value (V) bit. In addition, all bytes in memory, but
not in the CPU, have an associated valid-address (A) bit. This
indicates whether or not the program can legitimately read or write that
location. It does not give any indication of the validity of the data
at that location — that’s the job of the V bits — only whether or not
the location may be accessed.

Every time your program reads or writes memory, Memcheck checks
the A bits associated with the address. If any of them indicate an
invalid address, an error is emitted. Note that the reads and writes
themselves do not change the A bits, only consult them.

So how do the A bits get set/cleared? Like this:

  • When the program starts, all the global data areas are
    marked as accessible.

  • When the program does
    malloc/new,
    the A bits for exactly the area allocated, and not a byte more,
    are marked as accessible. Upon freeing the area the A bits are
    changed to indicate inaccessibility.

  • When the stack pointer register (SP) moves
    up or down, A bits are set. The rule is that the area from
    SP up to the base of the stack is marked as
    accessible, and below SP is inaccessible. (If
    that sounds illogical, bear in mind that the stack grows down, not
    up, on almost all Unix systems, including GNU/Linux.) Tracking
    SP like this has the useful side-effect that the
    section of stack used by a function for local variables etc is
    automatically marked accessible on function entry and inaccessible
    on exit.

  • When doing system calls, A bits are changed appropriately.
    For example, mmap
    magically makes files appear in the process’
    address space, so the A bits must be updated if mmap
    succeeds.

  • Optionally, your program can tell Memcheck about such changes
    explicitly, using the client request mechanism described
    above.

4.5.3. Putting it all together

Memcheck’s checking machinery can be summarised as
follows:

  • Each byte in memory has 8 associated V (valid-value) bits,
    saying whether or not the byte has a defined value, and a single A
    (valid-address) bit, saying whether or not the program currently has
    the right to read/write that address. As mentioned above, heavy
    use of compression means the overhead is typically around 25%.

  • When memory is read or written, the relevant A bits are
    consulted. If they indicate an invalid address, Memcheck emits an
    Invalid read or Invalid write error.

  • When memory is read into the CPU’s registers, the relevant V
    bits are fetched from memory and stored in the simulated CPU. They
    are not consulted.

  • When a register is written out to memory, the V bits for that
    register are written back to memory too.

  • When values in CPU registers are used to generate a memory
    address, or to determine the outcome of a conditional branch, the V
    bits for those values are checked, and an error emitted if any of
    them are undefined.

  • When values in CPU registers are used for any other purpose,
    Memcheck computes the V bits for the result, but does not check
    them.

  • Once the V bits for a value in the CPU have been checked, they
    are then set to indicate validity. This avoids long chains of
    errors.

  • When values are loaded from memory, Memcheck checks the A bits
    for that location and issues an illegal-address warning if needed.
    In that case, the V bits loaded are forced to indicate Valid,
    despite the location being invalid.

    This apparently strange choice reduces the amount of confusing
    information presented to the user. It avoids the unpleasant
    phenomenon in which memory is read from a place which is both
    unaddressable and contains invalid values, and, as a result, you get
    not only an invalid-address (read/write) error, but also a
    potentially large set of uninitialised-value errors, one for every
    time the value is used.

    There is a hazy boundary case to do with multi-byte loads from
    addresses which are partially valid and partially invalid. See
    details of the option --partial-loads-ok for details.

Memcheck intercepts calls to malloc,
calloc, realloc,
valloc, memalign,
free, new,
new[],
delete and
delete[]. The behaviour you get
is:

  • malloc/new/new[]:
    the returned memory is marked as addressable but not having valid
    values. This means you have to write to it before you can read
    it.

  • calloc: returned memory is marked both
    addressable and valid, since calloc clears
    the area to zero.

  • realloc: if the new size is larger than
    the old, the new section is addressable but invalid, as with
    malloc. If the new size is smaller, the
    dropped-off section is marked as unaddressable. You may only pass to
    realloc a pointer previously issued to you by
    malloc/calloc/realloc.

  • free/delete/delete[]:
    you may only pass to these functions a pointer previously issued
    to you by the corresponding allocation function. Otherwise,
    Memcheck complains. If the pointer is indeed valid, Memcheck
    marks the entire area it points at as unaddressable, and places
    the block in the freed-blocks-queue. The aim is to defer as long
    as possible reallocation of this block. Until that happens, all
    attempts to access it will elicit an invalid-address error, as you
    would hope.

4.6. Memcheck Monitor Commands

The Memcheck tool provides monitor commands handled by Valgrind’s
built-in gdbserver (see Monitor command handling by the Valgrind gdbserver).

  • xb <addr> [<len>]
    shows the definedness (V) bits and values for <len> (default 1)
    bytes starting at <addr>.
    For each 8 bytes, two lines are output.

    The first line shows the validity bits for 8 bytes.
    The definedness of each byte in the range is given using two hexadecimal
    digits. These hexadecimal digits encode the validity of each bit of the
    corresponding byte,
    using 0 if the bit is defined and 1 if the bit is undefined.
    If a byte is not addressable, its validity bits are replaced
    by __ (a double underscore).

    The second line shows the values of the bytes below the corresponding
    validity bits. The format used to show the bytes data is similar to the
    GDB command ‘x /<len>xb <addr>’. The value for a non
    addressable bytes is shown as ?? (two question marks).

    In the following example, string10 is an array
    of 10 characters, in which the even numbered bytes are
    undefined. In the below example, the byte corresponding
    to string10[5] is not addressable.

    (gdb) p &string10
    $4 = (char (*)[10]) 0x804a2f0
    (gdb) mo xb 0x804a2f0 10
                      ff      00      ff      00      ff      __      ff      00
    0x804A2F0:      0x3f    0x6e    0x3f    0x65    0x3f    0x??     0x3f    0x65
                      ff      00
    0x804A2F8:      0x3f    0x00
    Address 0x804A2F0 len 10 has 1 bytes unaddressable
    (gdb)
    

    The command xb cannot be used with registers. To get
    the validity bits of a register, you must start Valgrind with the
    option --vgdb-shadow-registers=yes. The validity
    bits of a register can then be obtained by printing the ‘shadow 1’
    corresponding register. In the below x86 example, the register
    eax has all its bits undefined, while the register ebx is fully
    defined.

    (gdb) p /x $eaxs1
    $9 = 0xffffffff
    (gdb) p /x $ebxs1
    $10 = 0x0
    (gdb) 
    
  • get_vbits <addr> [<len>]
    shows the definedness (V) bits for <len> (default 1) bytes
    starting at <addr> using the same convention as the
    xb command. get_vbits only
    shows the V bits (grouped by 4 bytes). It does not show the values.
    If you want to associate V bits with the corresponding byte values, the
    xb command will be easier to use, in particular
    on little endian computers when associating undefined parts of an integer
    with their V bits values.

    The following example shows the result of get_vibts
    on the string10 used in the xb
    command explanation.

    (gdb) monitor get_vbits 0x804a2f0 10
    ff00ff00 ff__ff00 ff00
    Address 0x804A2F0 len 10 has 1 bytes unaddressable
    (gdb) 
    
  • make_memory
    [noaccess|undefined|defined|Definedifaddressable] <addr>
    [<len>]
    marks the range of <len> (default 1)
    bytes at <addr> as having the given status. Parameter
    noaccess marks the range as non-accessible, so
    Memcheck will report an error on any access to it.
    undefined or defined mark
    the area as accessible, but Memcheck regards the bytes in it
    respectively as having undefined or defined values.
    Definedifaddressable marks as defined, bytes in
    the range which are already addressible, but makes no change to
    the status of bytes in the range which are not addressible. Note
    that the first letter of Definedifaddressable
    is an uppercase D to avoid confusion with defined.

    In the following example, the first byte of the
    string10 is marked as defined:

    (gdb) monitor make_memory defined 0x8049e28  1
    (gdb) monitor get_vbits 0x8049e28 10
    0000ff00 ff00ff00 ff00
    (gdb) 
    
  • check_memory [addressable|defined] <addr>
    [<len>]
    checks that the range of <len>
    (default 1) bytes at <addr> has the specified accessibility.
    It then outputs a description of <addr>. In the following
    example, a detailed description is available because the
    option --read-var-info=yes was given at Valgrind
    startup:

    (gdb) monitor check_memory defined 0x8049e28  1
    Address 0x8049E28 len 1 defined
    ==14698==  Location 0x8049e28 is 0 bytes inside string10[0],
    ==14698==  declared at prog.c:10, in frame #0 of thread 1
    (gdb) 
    
  • leak_check [full*|summary|xtleak]
    [kinds <set>|reachable|possibleleak*|definiteleak]
    [heuristics heur1,heur2,...]
    [increased*|changed|any]
    [unlimited*|limited <max_loss_records_output>]

    performs a leak check. The * in the arguments
    indicates the default values.

    If the [full*|summary|xtleak] argument is
    summary, only a summary of the leak search is given;
    otherwise a full leak report is produced. A full leak report gives
    detailed information for each leak: the stack trace where the leaked blocks
    were allocated, the number of blocks leaked and their total size. When a
    full report is requested, the next two arguments further specify what
    kind of leaks to report. A leak’s details are shown if they match
    both the second and third argument. A full leak report might
    output detailed information for many leaks. The nr of leaks for
    which information is output can be controlled using
    the limited argument followed by the maximum nr
    of leak records to output. If this maximum is reached, the leak
    search outputs the records with the biggest number of bytes.

    The value xtleak also produces a full leak report,
    but output it as an xtree in a file xtleak.kcg.%p.%n (see —log-file).
    See Execution Trees
    for a detailed explanation about execution trees formats.
    See —xtree-leak for the description of the events
    in a xtree leak file.

    The kinds argument controls what kind of blocks
    are shown for a full leak search. The set of leak kinds
    to show can be specified using a <set> similarly
    to the command line option --show-leak-kinds.
    Alternatively, the value definiteleak
    is equivalent to kinds definite, the
    value possibleleak is equivalent to
    kinds definite,possible : it will also show
    possibly leaked blocks, .i.e those for which only an interior
    pointer was found. The value reachable will
    show all block categories (i.e. is equivalent to kinds
    all
    ).

    The heuristics argument controls the heuristics
    used during the leak search. The set of heuristics to use can be specified
    using a <set> similarly
    to the command line option --leak-check-heuristics.
    The default value for the heuristics argument is
    heuristics none.

    The [increased*|changed|any] argument controls what
    kinds of changes are shown for a full leak search. The
    value increased specifies that only block
    allocation stacks with an increased number of leaked bytes or
    blocks since the previous leak check should be shown. The
    value changed specifies that allocation stacks
    with any change since the previous leak check should be shown.
    The value any specifies that all leak entries
    should be shown, regardless of any increase or decrease. When
    If increased or changed are
    specified, the leak report entries will show the delta relative to
    the previous leak report.

    The following example shows usage of the
    leak_check monitor command on
    the memcheck/tests/leak-cases.c regression
    test. The first command outputs one entry having an increase in
    the leaked bytes. The second command is the same as the first
    command, but uses the abbreviated forms accepted by GDB and the
    Valgrind gdbserver. It only outputs the summary information, as
    there was no increase since the previous leak search.

    (gdb) monitor leak_check full possibleleak increased
    ==19520== 16 (+16) bytes in 1 (+1) blocks are possibly lost in loss record 9 of 12
    ==19520==    at 0x40070B4: malloc (vg_replace_malloc.c:263)
    ==19520==    by 0x80484D5: mk (leak-cases.c:52)
    ==19520==    by 0x804855F: f (leak-cases.c:81)
    ==19520==    by 0x80488E0: main (leak-cases.c:107)
    ==19520== 
    ==19520== LEAK SUMMARY:
    ==19520==    definitely lost: 32 (+0) bytes in 2 (+0) blocks
    ==19520==    indirectly lost: 16 (+0) bytes in 1 (+0) blocks
    ==19520==      possibly lost: 32 (+16) bytes in 2 (+1) blocks
    ==19520==    still reachable: 96 (+16) bytes in 6 (+1) blocks
    ==19520==         suppressed: 0 (+0) bytes in 0 (+0) blocks
    ==19520== Reachable blocks (those to which a pointer was found) are not shown.
    ==19520== To see them, add 'reachable any' args to leak_check
    ==19520== 
    (gdb) mo l
    ==19520== LEAK SUMMARY:
    ==19520==    definitely lost: 32 (+0) bytes in 2 (+0) blocks
    ==19520==    indirectly lost: 16 (+0) bytes in 1 (+0) blocks
    ==19520==      possibly lost: 32 (+0) bytes in 2 (+0) blocks
    ==19520==    still reachable: 96 (+0) bytes in 6 (+0) blocks
    ==19520==         suppressed: 0 (+0) bytes in 0 (+0) blocks
    ==19520== Reachable blocks (those to which a pointer was found) are not shown.
    ==19520== To see them, add 'reachable any' args to leak_check
    ==19520== 
    (gdb) 
    

    Note that when using Valgrind’s gdbserver, it is not
    necessary to rerun
    with --leak-check=full
    --show-reachable=yes to see the reachable
    blocks. You can obtain the same information without rerunning by
    using the GDB command monitor leak_check full
    reachable any
    (or, using
    abbreviation: mo l f r a).

  • block_list <loss_record_nr>|<loss_record_nr_from>..<loss_record_nr_to>
    [unlimited*|limited <max_blocks>]
    [heuristics heur1,heur2,...]

    shows the list of blocks belonging to
    <loss_record_nr> (or to the loss records range
    <loss_record_nr_from>..<loss_record_nr_to>).
    The nr of blocks to print can be controlled using the
    limited argument followed by the maximum nr
    of blocks to output.
    If one or more heuristics are given, only prints the loss records
    and blocks found via one of the given heur1,heur2,...
    heuristics.

    A leak search merges the allocated blocks in loss records :
    a loss record re-groups all blocks having the same state (for
    example, Definitely Lost) and the same allocation backtrace.
    Each loss record is identified in the leak search result
    by a loss record number.
    The block_list command shows the loss record information
    followed by the addresses and sizes of the blocks which have been
    merged in the loss record. If a block was found using an heuristic, the block size
    is followed by the heuristic.

    If a directly lost block causes some other blocks to be indirectly
    lost, the block_list command will also show these indirectly lost blocks.
    The indirectly lost blocks will be indented according to the level of indirection
    between the directly lost block and the indirectly lost block(s).
    Each indirectly lost block is followed by the reference of its loss record.

    The block_list command can be used on the results of a leak search as long
    as no block has been freed after this leak search: as soon as the program frees
    a block, a new leak search is needed before block_list can be used again.

    In the below example, the program leaks a tree structure by losing the pointer to
    the block A (top of the tree).
    So, the block A is directly lost, causing an indirect
    loss of blocks B to G. The first block_list command shows the loss record of A
    (a definitely lost block with address 0x4028028, size 16). The addresses and sizes
    of the indirectly lost blocks due to block A are shown below the block A.
    The second command shows the details of one of the indirect loss records output
    by the first command.

               A
             /   
            B     C
           /    /  
          D   E F   G
    
    (gdb) bt
    #0  main () at leak-tree.c:69
    (gdb) monitor leak_check full any
    ==19552== 112 (16 direct, 96 indirect) bytes in 1 blocks are definitely lost in loss record 7 of 7
    ==19552==    at 0x40070B4: malloc (vg_replace_malloc.c:263)
    ==19552==    by 0x80484D5: mk (leak-tree.c:28)
    ==19552==    by 0x80484FC: f (leak-tree.c:41)
    ==19552==    by 0x8048856: main (leak-tree.c:63)
    ==19552== 
    ==19552== LEAK SUMMARY:
    ==19552==    definitely lost: 16 bytes in 1 blocks
    ==19552==    indirectly lost: 96 bytes in 6 blocks
    ==19552==      possibly lost: 0 bytes in 0 blocks
    ==19552==    still reachable: 0 bytes in 0 blocks
    ==19552==         suppressed: 0 bytes in 0 blocks
    ==19552== 
    (gdb) monitor block_list 7
    ==19552== 112 (16 direct, 96 indirect) bytes in 1 blocks are definitely lost in loss record 7 of 7
    ==19552==    at 0x40070B4: malloc (vg_replace_malloc.c:263)
    ==19552==    by 0x80484D5: mk (leak-tree.c:28)
    ==19552==    by 0x80484FC: f (leak-tree.c:41)
    ==19552==    by 0x8048856: main (leak-tree.c:63)
    ==19552== 0x4028028[16]
    ==19552==   0x4028068[16] indirect loss record 1
    ==19552==      0x40280E8[16] indirect loss record 3
    ==19552==      0x4028128[16] indirect loss record 4
    ==19552==   0x40280A8[16] indirect loss record 2
    ==19552==      0x4028168[16] indirect loss record 5
    ==19552==      0x40281A8[16] indirect loss record 6
    (gdb) mo b 2
    ==19552== 16 bytes in 1 blocks are indirectly lost in loss record 2 of 7
    ==19552==    at 0x40070B4: malloc (vg_replace_malloc.c:263)
    ==19552==    by 0x80484D5: mk (leak-tree.c:28)
    ==19552==    by 0x8048519: f (leak-tree.c:43)
    ==19552==    by 0x8048856: main (leak-tree.c:63)
    ==19552== 0x40280A8[16]
    ==19552==   0x4028168[16] indirect loss record 5
    ==19552==   0x40281A8[16] indirect loss record 6
    (gdb) 
    
    
  • who_points_at <addr> [<len>]
    shows all the locations where a pointer to addr is found.
    If len is equal to 1, the command only shows the locations pointing
    exactly at addr (i.e. the «start pointers» to addr).
    If len is > 1, «interior pointers» pointing at the len first bytes
    will also be shown.

    The locations searched for are the same as the locations
    used in the leak search. So, who_points_at can a.o.
    be used to show why the leak search still can reach a block, or can
    search for dangling pointers to a freed block.
    Each location pointing at addr (or pointing inside addr if interior pointers
    are being searched for) will be described.

    In the below example, the pointers to the ‘tree block A’ (see example
    in command block_list) is shown before the tree was leaked.
    The descriptions are detailed as the option --read-var-info=yes
    was given at Valgrind startup. The second call shows the pointers (start and interior
    pointers) to block G. The block G (0x40281A8) is reachable via block C (0x40280a8)
    and register ECX of tid 1 (tid is the Valgrind thread id).
    It is «interior reachable» via the register EBX.

    (gdb) monitor who_points_at 0x4028028
    ==20852== Searching for pointers to 0x4028028
    ==20852== *0x8049e20 points at 0x4028028
    ==20852==  Location 0x8049e20 is 0 bytes inside global var "t"
    ==20852==  declared at leak-tree.c:35
    (gdb) monitor who_points_at 0x40281A8 16
    ==20852== Searching for pointers pointing in 16 bytes from 0x40281a8
    ==20852== *0x40280ac points at 0x40281a8
    ==20852==  Address 0x40280ac is 4 bytes inside a block of size 16 alloc'd
    ==20852==    at 0x40070B4: malloc (vg_replace_malloc.c:263)
    ==20852==    by 0x80484D5: mk (leak-tree.c:28)
    ==20852==    by 0x8048519: f (leak-tree.c:43)
    ==20852==    by 0x8048856: main (leak-tree.c:63)
    ==20852== tid 1 register ECX points at 0x40281a8
    ==20852== tid 1 register EBX interior points at 2 bytes inside 0x40281a8
    (gdb)
    

    When who_points_at finds an interior pointer,
    it will report the heuristic(s) with which this interior pointer
    will be considered as reachable. Note that this is done independently
    of the value of the option --leak-check-heuristics.
    In the below example, the loss record 6 indicates a possibly lost
    block. who_points_at reports that there is an interior
    pointer pointing in this block, and that the block can be considered
    reachable using the heuristic
    multipleinheritance.

    (gdb) monitor block_list 6
    ==3748== 8 bytes in 1 blocks are possibly lost in loss record 6 of 7
    ==3748==    at 0x4007D77: operator new(unsigned int) (vg_replace_malloc.c:313)
    ==3748==    by 0x8048954: main (leak_cpp_interior.cpp:43)
    ==3748== 0x402A0E0[8]
    (gdb) monitor who_points_at 0x402A0E0 8
    ==3748== Searching for pointers pointing in 8 bytes from 0x402a0e0
    ==3748== *0xbe8ee078 interior points at 4 bytes inside 0x402a0e0
    ==3748==  Address 0xbe8ee078 is on thread 1's stack
    ==3748== block at 0x402a0e0 considered reachable by ptr 0x402a0e4 using multipleinheritance heuristic
    (gdb) 
    
  • xtmemory [<filename> default xtmemory.kcg.%p.%n]
    requests Memcheck tool to produce an xtree heap memory report.
    See Execution Trees for
    a detailed explanation about execution trees.

4.7. Client Requests

The following client requests are defined in
memcheck.h.
See memcheck.h for exact details of their
arguments.

  • VALGRIND_MAKE_MEM_NOACCESS,
    VALGRIND_MAKE_MEM_UNDEFINED and
    VALGRIND_MAKE_MEM_DEFINED.
    These mark address ranges as completely inaccessible,
    accessible but containing undefined data, and accessible and
    containing defined data, respectively. They return -1, when
    run on Valgrind and 0 otherwise.

  • VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE.
    This is just like VALGRIND_MAKE_MEM_DEFINED but only
    affects those bytes that are already addressable.

  • VALGRIND_CHECK_MEM_IS_ADDRESSABLE and
    VALGRIND_CHECK_MEM_IS_DEFINED: check immediately
    whether or not the given address range has the relevant property,
    and if not, print an error message. Also, for the convenience of
    the client, returns zero if the relevant property holds; otherwise,
    the returned value is the address of the first byte for which the
    property is not true. Always returns 0 when not run on
    Valgrind.

  • VALGRIND_CHECK_VALUE_IS_DEFINED: a quick and easy
    way to find out whether Valgrind thinks a particular value
    (lvalue, to be precise) is addressable and defined. Prints an error
    message if not. It has no return value.

  • VALGRIND_DO_LEAK_CHECK: does a full memory leak
    check (like --leak-check=full) right now.
    This is useful for incrementally checking for leaks between arbitrary
    places in the program’s execution. It has no return value.

  • VALGRIND_DO_ADDED_LEAK_CHECK: same as
    VALGRIND_DO_LEAK_CHECK but only shows the
    entries for which there was an increase in leaked bytes or leaked
    number of blocks since the previous leak search. It has no return
    value.

  • VALGRIND_DO_CHANGED_LEAK_CHECK: same as
    VALGRIND_DO_LEAK_CHECK but only shows the
    entries for which there was an increase or decrease in leaked
    bytes or leaked number of blocks since the previous leak search. It
    has no return value.

  • VALGRIND_DO_QUICK_LEAK_CHECK: like
    VALGRIND_DO_LEAK_CHECK, except it produces only a leak
    summary (like --leak-check=summary).
    It has no return value.

  • VALGRIND_COUNT_LEAKS: fills in the four
    arguments with the number of bytes of memory found by the previous
    leak check to be leaked (i.e. the sum of direct leaks and indirect leaks),
    dubious, reachable and suppressed. This is useful in test harness code,
    after calling VALGRIND_DO_LEAK_CHECK or
    VALGRIND_DO_QUICK_LEAK_CHECK.

  • VALGRIND_COUNT_LEAK_BLOCKS: identical to
    VALGRIND_COUNT_LEAKS except that it returns the
    number of blocks rather than the number of bytes in each
    category.

  • VALGRIND_GET_VBITS and
    VALGRIND_SET_VBITS: allow you to get and set the
    V (validity) bits for an address range. You should probably only
    set V bits that you have got with
    VALGRIND_GET_VBITS. Only for those who really
    know what they are doing.

  • VALGRIND_CREATE_BLOCK and
    VALGRIND_DISCARD. VALGRIND_CREATE_BLOCK
    takes an address, a number of bytes and a character string. The
    specified address range is then associated with that string. When
    Memcheck reports an invalid access to an address in the range, it
    will describe it in terms of this block rather than in terms of
    any other block it knows about. Note that the use of this macro
    does not actually change the state of memory in any way — it
    merely gives a name for the range.

    At some point you may want Memcheck to stop reporting errors
    in terms of the block named
    by VALGRIND_CREATE_BLOCK. To make this
    possible, VALGRIND_CREATE_BLOCK returns a
    «block handle», which is a C int value. You
    can pass this block handle to VALGRIND_DISCARD.
    After doing so, Valgrind will no longer relate addressing errors
    in the specified range to the block. Passing invalid handles to
    VALGRIND_DISCARD is harmless.

4.8. Memory Pools: describing and working with custom allocators

Some programs use custom memory allocators, often for performance
reasons. Left to itself, Memcheck is unable to understand the
behaviour of custom allocation schemes as well as it understands the
standard allocators, and so may miss errors and leaks in your program. What
this section describes is a way to give Memcheck enough of a description of
your custom allocator that it can make at least some sense of what is
happening.

There are many different sorts of custom allocator, so Memcheck
attempts to reason about them using a loose, abstract model. We
use the following terminology when describing custom allocation
systems:

  • Custom allocation involves a set of independent «memory pools».

  • Memcheck’s notion of a a memory pool consists of a single «anchor
    address» and a set of non-overlapping «chunks» associated with the
    anchor address.

  • Typically a pool’s anchor address is the address of a
    book-keeping «header» structure.

  • Typically the pool’s chunks are drawn from a contiguous
    «superblock» acquired through the system
    malloc or
    mmap.

Keep in mind that the last two points above say «typically»: the
Valgrind mempool client request API is intentionally vague about the
exact structure of a mempool. There is no specific mention made of
headers or superblocks. Nevertheless, the following picture may help
elucidate the intention of the terms in the API:

   "pool"
   (anchor address)
   |
   v
   +--------+---+
   | header | o |
   +--------+-|-+
              |
              v                  superblock
              +------+---+--------------+---+------------------+
              |      |rzB|  allocation  |rzB|                  |
              +------+---+--------------+---+------------------+
                         ^              ^
                         |              |
                       "addr"     "addr"+"size"

Note that the header and the superblock may be contiguous or
discontiguous, and there may be multiple superblocks associated with a
single header; such variations are opaque to Memcheck. The API
only requires that your allocation scheme can present sensible values
of «pool», «addr» and «size».

Typically, before making client requests related to mempools, a client
program will have allocated such a header and superblock for their
mempool, and marked the superblock NOACCESS using the
VALGRIND_MAKE_MEM_NOACCESS client request.

When dealing with mempools, the goal is to maintain a particular
invariant condition: that Memcheck believes the unallocated portions
of the pool’s superblock (including redzones) are NOACCESS. To
maintain this invariant, the client program must ensure that the
superblock starts out in that state; Memcheck cannot make it so, since
Memcheck never explicitly learns about the superblock of a pool, only
the allocated chunks within the pool.

Once the header and superblock for a pool are established and properly
marked, there are a number of client requests programs can use to
inform Memcheck about changes to the state of a mempool:

  • VALGRIND_CREATE_MEMPOOL(pool, rzB, is_zeroed):
    This request registers the address pool as the anchor
    address for a memory pool. It also provides a size
    rzB, specifying how large the redzones placed around
    chunks allocated from the pool should be. Finally, it provides an
    is_zeroed argument that specifies whether the pool’s
    chunks are zeroed (more precisely: defined) when allocated.

    Upon completion of this request, no chunks are associated with the
    pool. The request simply tells Memcheck that the pool exists, so that
    subsequent calls can refer to it as a pool.

  • VALGRIND_CREATE_MEMPOOL_EXT(pool, rzB, is_zeroed, flags):
    Create a memory pool with some flags (that can
    be OR-ed together) specifying extended behaviour. When flags is
    zero, the behaviour is identical to
    VALGRIND_CREATE_MEMPOOL.

    • The flag VALGRIND_MEMPOOL_METAPOOL
      specifies that the pieces of memory associated with the pool
      using VALGRIND_MEMPOOL_ALLOC will be used
      by the application as superblocks to dole out MALLOC_LIKE
      blocks using VALGRIND_MALLOCLIKE_BLOCK.
      In other words, a meta pool is a «2 levels» pool : first
      level is the blocks described
      by VALGRIND_MEMPOOL_ALLOC. The second
      level blocks are described
      using VALGRIND_MALLOCLIKE_BLOCK. Note
      that the association between the pool and the second level
      blocks is implicit : second level blocks will be located
      inside first level blocks. It is necessary to use
      the VALGRIND_MEMPOOL_METAPOOL flag for
      such 2 levels pools, as otherwise valgrind will detect
      overlapping memory blocks, and will abort execution
      (e.g. during leak search).

    • VALGRIND_MEMPOOL_AUTO_FREE. Such a meta
      pool can also be marked as an ‘auto free’ pool using the
      flag VALGRIND_MEMPOOL_AUTO_FREE, which
      must be OR-ed together with
      the VALGRIND_MEMPOOL_METAPOOL. For an
      ‘auto free’ pool, VALGRIND_MEMPOOL_FREE
      will automatically free the second level blocks that are
      contained inside the first level block freed
      with VALGRIND_MEMPOOL_FREE. In other
      words, calling VALGRIND_MEMPOOL_FREE will
      cause implicit calls
      to VALGRIND_FREELIKE_BLOCK for all the
      second level blocks included in the first level block.
      Note: it is an error to use
      the VALGRIND_MEMPOOL_AUTO_FREE flag
      without the
      VALGRIND_MEMPOOL_METAPOOL flag.

  • VALGRIND_DESTROY_MEMPOOL(pool):
    This request tells Memcheck that a pool is being torn down. Memcheck
    then removes all records of chunks associated with the pool, as well
    as its record of the pool’s existence. While destroying its records of
    a mempool, Memcheck resets the redzones of any live chunks in the pool
    to NOACCESS.

  • VALGRIND_MEMPOOL_ALLOC(pool, addr, size):
    This request informs Memcheck that a size-byte chunk
    has been allocated at addr, and associates the chunk with the
    specified
    pool. If the pool was created with nonzero
    rzB redzones, Memcheck will mark the
    rzB bytes before and after the chunk as NOACCESS. If
    the pool was created with the is_zeroed argument set,
    Memcheck will mark the chunk as DEFINED, otherwise Memcheck will mark
    the chunk as UNDEFINED.

  • VALGRIND_MEMPOOL_FREE(pool, addr):
    This request informs Memcheck that the chunk at addr
    should no longer be considered allocated. Memcheck will mark the chunk
    associated with addr as NOACCESS, and delete its
    record of the chunk’s existence.

  • VALGRIND_MEMPOOL_TRIM(pool, addr, size):
    This request trims the chunks associated with pool.
    The request only operates on chunks associated with
    pool. Trimming is formally defined as:

    • All chunks entirely inside the range
      addr..(addr+size-1) are preserved.

    • All chunks entirely outside the range
      addr..(addr+size-1) are discarded, as though
      VALGRIND_MEMPOOL_FREE was called on them.

    • All other chunks must intersect with the range
      addr..(addr+size-1); areas outside the
      intersection are marked as NOACCESS, as though they had been
      independently freed with
      VALGRIND_MEMPOOL_FREE.

    This is a somewhat rare request, but can be useful in
    implementing the type of mass-free operations common in custom
    LIFO allocators.

  • VALGRIND_MOVE_MEMPOOL(poolA, poolB): This
    request informs Memcheck that the pool previously anchored at
    address poolA has moved to anchor address
    poolB. This is a rare request, typically only needed
    if you realloc the header of a mempool.

    No memory-status bits are altered by this request.

  • VALGRIND_MEMPOOL_CHANGE(pool, addrA, addrB,
    size)
    : This request informs Memcheck that the chunk
    previously allocated at address addrA within
    pool has been moved and/or resized, and should be
    changed to cover the region addrB..(addrB+size-1). This
    is a rare request, typically only needed if you
    realloc a superblock or wish to extend a chunk
    without changing its memory-status bits.

    No memory-status bits are altered by this request.

  • VALGRIND_MEMPOOL_EXISTS(pool):
    This request informs the caller whether or not Memcheck is currently
    tracking a mempool at anchor address pool. It
    evaluates to 1 when there is a mempool associated with that address, 0
    otherwise. This is a rare request, only useful in circumstances when
    client code might have lost track of the set of active mempools.

4.9. Debugging MPI Parallel Programs with Valgrind

Memcheck supports debugging of distributed-memory applications
which use the MPI message passing standard. This support consists of a
library of wrapper functions for the
PMPI_* interface. When incorporated
into the application’s address space, either by direct linking or by
LD_PRELOAD, the wrappers intercept
calls to PMPI_Send,
PMPI_Recv, etc. They then
use client requests to inform Memcheck of memory state changes caused
by the function being wrapped. This reduces the number of false
positives that Memcheck otherwise typically reports for MPI
applications.

The wrappers also take the opportunity to carefully check
size and definedness of buffers passed as arguments to MPI functions, hence
detecting errors such as passing undefined data to
PMPI_Send, or receiving data into a
buffer which is too small.

Unlike most of the rest of Valgrind, the wrapper library is subject to a
BSD-style license, so you can link it into any code base you like.
See the top of mpi/libmpiwrap.c
for license details.

4.9.1. Building and installing the wrappers

The wrapper library will be built automatically if possible.
Valgrind’s configure script will look for a suitable
mpicc to build it with. This must be
the same mpicc you use to build the
MPI application you want to debug. By default, Valgrind tries
mpicc, but you can specify a
different one by using the configure-time option
--with-mpicc. Currently the
wrappers are only buildable with
mpiccs which are based on GNU
GCC or Intel’s C++ Compiler.

Check that the configure script prints a line like this:

checking for usable MPI2-compliant mpicc and mpi.h... yes, mpicc

If it says ... no, your
mpicc has failed to compile and link
a test MPI2 program.

If the configure test succeeds, continue in the usual way with
make and make
install
. The final install tree should then contain
libmpiwrap-<platform>.so.

Compile up a test MPI program (eg, MPI hello-world) and try
this:

LD_PRELOAD=$prefix/lib/valgrind/libmpiwrap-<platform>.so   
           mpirun [args] $prefix/bin/valgrind ./hello

You should see something similar to the following

valgrind MPI wrappers 31901: Active for pid 31901
valgrind MPI wrappers 31901: Try MPIWRAP_DEBUG=help for possible options

repeated for every process in the group. If you do not see
these, there is an build/installation problem of some kind.

The MPI functions to be wrapped are assumed to be in an ELF
shared object with soname matching
libmpi.so*. This is known to be
correct at least for Open MPI and Quadrics MPI, and can easily be
changed if required.

4.9.2. Getting started

Compile your MPI application as usual, taking care to link it
using the same mpicc that your
Valgrind build was configured with.

Use the following basic scheme to run your application on Valgrind with
the wrappers engaged:

MPIWRAP_DEBUG=[wrapper-args]                                  
   LD_PRELOAD=$prefix/lib/valgrind/libmpiwrap-<platform>.so   
   mpirun [mpirun-args]                                       
   $prefix/bin/valgrind [valgrind-args]                       
   [application] [app-args]

As an alternative to
LD_PRELOADing
libmpiwrap-<platform>.so, you can
simply link it to your application if desired. This should not disturb
native behaviour of your application in any way.

4.9.3. Controlling the wrapper library

Environment variable
MPIWRAP_DEBUG is consulted at
startup. The default behaviour is to print a starting banner

valgrind MPI wrappers 16386: Active for pid 16386
valgrind MPI wrappers 16386: Try MPIWRAP_DEBUG=help for possible options

and then be relatively quiet.

You can give a list of comma-separated options in
MPIWRAP_DEBUG. These are

  • verbose:
    show entries/exits of all wrappers. Also show extra
    debugging info, such as the status of outstanding
    MPI_Requests resulting
    from uncompleted MPI_Irecvs.

  • quiet:
    opposite of verbose, only print
    anything when the wrappers want
    to report a detected programming error, or in case of catastrophic
    failure of the wrappers.

  • warn:
    by default, functions which lack proper wrappers
    are not commented on, just silently
    ignored. This causes a warning to be printed for each unwrapped
    function used, up to a maximum of three warnings per function.

  • strict:
    print an error message and abort the program if
    a function lacking a wrapper is used.

If you want to use Valgrind’s XML output facility
(--xml=yes), you should pass
quiet in
MPIWRAP_DEBUG so as to get rid of any
extraneous printing from the wrappers.

4.9.4. Functions

All MPI2 functions except
MPI_Wtick,
MPI_Wtime and
MPI_Pcontrol have wrappers. The
first two are not wrapped because they return a
double, which Valgrind’s
function-wrap mechanism cannot handle (but it could easily be
extended to do so). MPI_Pcontrol cannot be
wrapped as it has variable arity:
int MPI_Pcontrol(const int level, ...)

Most functions are wrapped with a default wrapper which does
nothing except complain or abort if it is called, depending on
settings in MPIWRAP_DEBUG listed
above. The following functions have «real», do-something-useful
wrappers:

PMPI_Send PMPI_Bsend PMPI_Ssend PMPI_Rsend

PMPI_Recv PMPI_Get_count

PMPI_Isend PMPI_Ibsend PMPI_Issend PMPI_Irsend

PMPI_Irecv
PMPI_Wait PMPI_Waitall
PMPI_Test PMPI_Testall

PMPI_Iprobe PMPI_Probe

PMPI_Cancel

PMPI_Sendrecv

PMPI_Type_commit PMPI_Type_free

PMPI_Pack PMPI_Unpack

PMPI_Bcast PMPI_Gather PMPI_Scatter PMPI_Alltoall
PMPI_Reduce PMPI_Allreduce PMPI_Op_create

PMPI_Comm_create PMPI_Comm_dup PMPI_Comm_free PMPI_Comm_rank PMPI_Comm_size

PMPI_Error_string
PMPI_Init PMPI_Initialized PMPI_Finalize

A few functions such as
PMPI_Address are listed as
HAS_NO_WRAPPER. They have no wrapper
at all as there is nothing worth checking, and giving a no-op wrapper
would reduce performance for no reason.

Note that the wrapper library itself can itself generate large
numbers of calls to the MPI implementation, especially when walking
complex types. The most common functions called are
PMPI_Extent,
PMPI_Type_get_envelope,
PMPI_Type_get_contents, and
PMPI_Type_free.

4.9.5. Types

MPI-1.1 structured types are supported, and walked exactly.
The currently supported combiners are
MPI_COMBINER_NAMED,
MPI_COMBINER_CONTIGUOUS,
MPI_COMBINER_VECTOR,
MPI_COMBINER_HVECTOR
MPI_COMBINER_INDEXED,
MPI_COMBINER_HINDEXED and
MPI_COMBINER_STRUCT. This should
cover all MPI-1.1 types. The mechanism (function
walk_type) should extend easily to
cover MPI2 combiners.

MPI defines some named structured types
(MPI_FLOAT_INT,
MPI_DOUBLE_INT,
MPI_LONG_INT,
MPI_2INT,
MPI_SHORT_INT,
MPI_LONG_DOUBLE_INT) which are pairs
of some basic type and a C int.
Unfortunately the MPI specification makes it impossible to look inside
these types and see where the fields are. Therefore these wrappers
assume the types are laid out as struct { float val;
int loc; }
(for
MPI_FLOAT_INT), etc, and act
accordingly. This appears to be correct at least for Open MPI 1.0.2
and for Quadrics MPI.

If strict is an option specified
in MPIWRAP_DEBUG, the application
will abort if an unhandled type is encountered. Otherwise, the
application will print a warning message and continue.

Some effort is made to mark/check memory ranges corresponding to
arrays of values in a single pass. This is important for performance
since asking Valgrind to mark/check any range, no matter how small,
carries quite a large constant cost. This optimisation is applied to
arrays of primitive types (double,
float,
int,
long, long
long
, short,
char, and long
double
on platforms where sizeof(long
double) == 8
). For arrays of all other types, the
wrappers handle each element individually and so there can be a very
large performance cost.

4.9.6. Writing new wrappers

For the most part the wrappers are straightforward. The only
significant complexity arises with nonblocking receives.

The issue is that MPI_Irecv
states the recv buffer and returns immediately, giving a handle
(MPI_Request) for the transaction.
Later the user will have to poll for completion with
MPI_Wait etc, and when the
transaction completes successfully, the wrappers have to paint the
recv buffer. But the recv buffer details are not presented to
MPI_Wait — only the handle is. The
library therefore maintains a shadow table which associates
uncompleted MPI_Requests with the
corresponding buffer address/count/type. When an operation completes,
the table is searched for the associated address/count/type info, and
memory is marked accordingly.

Access to the table is guarded by a (POSIX pthreads) lock, so as
to make the library thread-safe.

The table is allocated with
malloc and never
freed, so it will show up in leak
checks.

Writing new wrappers should be fairly easy. The source file is
mpi/libmpiwrap.c. If possible,
find an existing wrapper for a function of similar behaviour to the
one you want to wrap, and use it as a starting point. The wrappers
are organised in sections in the same order as the MPI 1.1 spec, to
aid navigation. When adding a wrapper, remember to comment out the
definition of the default wrapper in the long list of defaults at the
bottom of the file (do not remove it, just comment it out).

4.9.7. What to expect when using the wrappers

The wrappers should reduce Memcheck’s false-error rate on MPI
applications. Because the wrapping is done at the MPI interface,
there will still potentially be a large number of errors reported in
the MPI implementation below the interface. The best you can do is
try to suppress them.

You may also find that the input-side (buffer
length/definedness) checks find errors in your MPI use, for example
passing too short a buffer to
MPI_Recv.

Functions which are not wrapped may increase the false
error rate. A possible approach is to run with
MPI_DEBUG containing
warn. This will show you functions
which lack proper wrappers but which are nevertheless used. You can
then write wrappers for them.

A known source of potential false errors are the
PMPI_Reduce family of functions, when
using a custom (user-defined) reduction function. In a reduction
operation, each node notionally sends data to a «central point» which
uses the specified reduction function to merge the data items into a
single item. Hence, in general, data is passed between nodes and fed
to the reduction function, but the wrapper library cannot mark the
transferred data as initialised before it is handed to the reduction
function, because all that happens «inside» the
PMPI_Reduce call. As a result you
may see false positives reported in your reduction function.

One major aspect of system programming is to handle memory related issues effectively. The more you work close to the system, the more memory related issues you need to face.

Sometimes these issues are very trivial while many times it becomes a nightmare to debug memory related issues. So, as a practice many tools are used for debugging memory related issues.

In this article, we will discuss the most popular open source memory management framework VALGRIND.

From Valgrind.org :

Valgrind is an instrumentation framework for building dynamic analysis tools. It comes with a set of tools each of which performs some kind of debugging, profiling, or similar task that helps you improve your programs. Valgrind’s architecture is modular, so new tools can be created easily and without disturbing the existing structure.

A number of useful tools are supplied as standard.

  1. Memcheck is a memory error detector. It helps you make your programs, particularly those written in C and C++, more correct.
  2. Cachegrind is a cache and branch-prediction profiler. It helps you make your programs run faster.
  3. Callgrind is a call-graph generating cache profiler. It has some overlap with Cachegrind, but also gathers some information that Cachegrind does not.
  4. Helgrind is a thread error detector. It helps you make your multi-threaded programs more correct.
  5. DRD is also a thread error detector. It is similar to Helgrind but uses different analysis techniques and so may find different problems.
  6. Massif is a heap profiler. It helps you make your programs use less memory.
  7. DHAT is a different kind of heap profiler. It helps you understand issues of block lifetimes, block utilisation, and layout inefficiencies.
  8. SGcheck is an experimental tool that can detect overruns of stack and global arrays. Its functionality is complementary to that of Memcheck: SGcheck finds problems that Memcheck can’t, and vice versa..
  9. BBV is an experimental SimPoint basic block vector generator. It is useful to people doing computer architecture research and development.

There are also a couple of minor tools that aren’t useful to most users: Lackey is an example tool that illustrates some instrumentation basics; and Nulgrind is the minimal Valgrind tool that does no analysis or instrumentation, and is only useful for testing purposes.

Here in this article we will focus on the tool ‘memcheck’.

Using Valgrind Memcheck

The memcheck tool is used as follows :

valgrind --tool=memcheck ./a.out

As clear from the command above, the main binary is ‘Valgrind’ and the tool which we want to use is specified by the option ‘–tool’. The ‘a.out’ above signifies the executable over which we want to run memcheck.

This tool can detect the following memory related problems :

  • Use of uninitialized memory
  • Reading/writing memory after it has been freed
  • Reading/writing off the end of malloc’d blocks
  • Memory leaks
  • Mismatched use of malloc/new/new[] vs free/delete/delete[]
  • Doubly freed memory

Note : The above list is not exhaustive but contains the popular problems detected by this tool.

Lets discuss the above scenarios one by one:

Note : All the test code described below should be compiled using gcc with -g option(to generate line numbers in memcheck output) enabled. As we discussed earlier for a C program to get compiled into an executable, it has to go through 4 different stages.

1. Use of uninitialized memory

Code :

#include <stdio.h>
#include <stdlib.h> 

int main(void)
{
    char *p; 

    char c = *p; 

    printf("n [%c]n",c); 

    return 0;
}

In the above code, we try to use an uninitialized pointer ‘p’.

Lets run memcheck and see the result.

$ valgrind --tool=memcheck ./val
==2862== Memcheck, a memory error detector
==2862== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==2862== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==2862== Command: ./val
==2862==
==2862== Use of uninitialised value of size 8
==2862==    at 0x400530: main (valgrind.c:8)
==2862==

[#]
==2862==
==2862== HEAP SUMMARY:
==2862==     in use at exit: 0 bytes in 0 blocks
==2862==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==2862==
==2862== All heap blocks were freed -- no leaks are possible
==2862==
==2862== For counts of detected and suppressed errors, rerun with: -v
==2862== Use --track-origins=yes to see where uninitialized values come from
==2862== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

As seen from the output above, Valgrind detects the uninitialized variable and gives a warning(see the lines in bold above).

2. Reading/writing memory after it has been freed

Code :

#include <stdio.h>
#include <stdlib.h> 

int main(void)
{
    char *p = malloc(1);
    *p = 'a'; 

    char c = *p; 

    printf("n [%c]n",c); 

    free(p);
    c = *p;
    return 0;
}

In the above piece of code, we have freed a pointer ‘p’ and then again we have tried to access the value help by the pointer.

Lets run memcheck and see what Valgrind has to offer for this scenario.

$ valgrind --tool=memcheck ./val
==2849== Memcheck, a memory error detector
==2849== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==2849== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==2849== Command: ./val
==2849== 

 [a]
==2849== Invalid read of size 1
==2849==    at 0x400603: main (valgrind.c:30)
==2849==  Address 0x51b0040 is 0 bytes inside a block of size 1 free'd
==2849==    at 0x4C270BD: free (vg_replace_malloc.c:366)
==2849==    by 0x4005FE: main (valgrind.c:29)
==2849==
==2849==
==2849== HEAP SUMMARY:
==2849==     in use at exit: 0 bytes in 0 blocks
==2849==   total heap usage: 1 allocs, 1 frees, 1 bytes allocated
==2849==
==2849== All heap blocks were freed -- no leaks are possible
==2849==
==2849== For counts of detected and suppressed errors, rerun with: -v
==2849== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

As seen in the output above, the tool detects the invalid read and prints the warning ‘Invalid read of size 1’.

On a side note, to debug a c program use gdb.

3. Reading/writing off the end of malloc’d blocks

Code :

#include <stdio.h>
#include <stdlib.h> 

int main(void)
{
    char *p = malloc(1);
    *p = 'a'; 

    char c = *(p+1); 

    printf("n [%c]n",c); 

    free(p);
    return 0;
}

In the above piece of code, we have allocated 1 byte for ‘p’ but we access the the address p+1 while reading the value into ‘c’.

Now we run Valgrind on this piece of code :

$ valgrind --tool=memcheck ./val
==2835== Memcheck, a memory error detector
==2835== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==2835== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==2835== Command: ./val
==2835==
==2835== Invalid read of size 1
==2835==    at 0x4005D9: main (valgrind.c:25)
==2835==  Address 0x51b0041 is 0 bytes after a block of size 1 alloc'd
==2835==    at 0x4C274A8: malloc (vg_replace_malloc.c:236)
==2835==    by 0x4005C5: main (valgrind.c:22)
==2835== 

 []
==2835==
==2835== HEAP SUMMARY:
==2835==     in use at exit: 0 bytes in 0 blocks
==2835==   total heap usage: 1 allocs, 1 frees, 1 bytes allocated
==2835==
==2835== All heap blocks were freed -- no leaks are possible
==2835==
==2835== For counts of detected and suppressed errors, rerun with: -v
==2835== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

Again, this tool detects the invalid read done in this case.

4. Memory leaks

Code:

#include <stdio.h>
#include <stdlib.h> 

int main(void)
{
    char *p = malloc(1);
    *p = 'a'; 

    char c = *p; 

    printf("n [%c]n",c); 

    return 0;
}

In this code, we have malloced one byte but haven’t freed it. Now lets run Valgrind and see what happens :

$ valgrind --tool=memcheck --leak-check=full ./val
==2888== Memcheck, a memory error detector
==2888== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==2888== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==2888== Command: ./val
==2888== 

 [a]
==2888==
==2888== HEAP SUMMARY:
==2888==     in use at exit: 1 bytes in 1 blocks
==2888==   total heap usage: 1 allocs, 0 frees, 1 bytes allocated
==2888==
==2888== 1 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2888==    at 0x4C274A8: malloc (vg_replace_malloc.c:236)
==2888==    by 0x400575: main (valgrind.c:6)
==2888==
==2888== LEAK SUMMARY:
==2888==    definitely lost: 1 bytes in 1 blocks
==2888==    indirectly lost: 0 bytes in 0 blocks
==2888==      possibly lost: 0 bytes in 0 blocks
==2888==    still reachable: 0 bytes in 0 blocks
==2888==         suppressed: 0 bytes in 0 blocks
==2888==
==2888== For counts of detected and suppressed errors, rerun with: -v
==2888== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

The lines (in bold above) shows that this tool was able to detect the leaked memory.

Note: In this case we added an extra option ‘–leak-check=full’ to get verbose details of the memory leak.

5. Mismatched use of malloc/new/new[] vs free/delete/delete[]

Code:

#include <stdio.h>
#include <stdlib.h>
#include<iostream> 

int main(void)
{
    char *p = (char*)malloc(1);
    *p = 'a'; 

    char c = *p; 

    printf("n [%c]n",c);
    delete p;
    return 0;
}

In the above code, we have used malloc() to allocate memory but used delete operator to delete the memory.

Note : Use g++ to compile the above code as delete operator was introduced in C++ and to compile c++ code, g++ tool is used.

Lets run this tool and see :

$ valgrind --tool=memcheck --leak-check=full ./val
==2972== Memcheck, a memory error detector
==2972== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==2972== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==2972== Command: ./val
==2972== 

 [a]
==2972== Mismatched free() / delete / delete []
==2972==    at 0x4C26DCF: operator delete(void*) (vg_replace_malloc.c:387)
==2972==    by 0x40080B: main (valgrind.c:13)
==2972==  Address 0x595e040 is 0 bytes inside a block of size 1 alloc'd
==2972==    at 0x4C274A8: malloc (vg_replace_malloc.c:236)
==2972==    by 0x4007D5: main (valgrind.c:7)
==2972==
==2972==
==2972== HEAP SUMMARY:
==2972==     in use at exit: 0 bytes in 0 blocks
==2972==   total heap usage: 1 allocs, 1 frees, 1 bytes allocated
==2972==
==2972== All heap blocks were freed -- no leaks are possible
==2972==
==2972== For counts of detected and suppressed errors, rerun with: -v
==2972== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

We see from the output above (see lines in bold), the tool clearly states ‘Mismatched free() / delete / delete []’

You can try and use the combination ‘new’ and ‘free’ in a test code and see what result this tool gives.

6. Doubly freed memory

Code :

#include <stdio.h>
#include <stdlib.h> 

int main(void)
{
    char *p = (char*)malloc(1);
    *p = 'a'; 

    char c = *p;
    printf("n [%c]n",c);
    free(p);
    free(p);
    return 0;
}

In the above peice of code, we have freed the memory pointed by ‘p’ twice. Now, lets run the tool memcheck :

$ valgrind --tool=memcheck --leak-check=full ./val
==3167== Memcheck, a memory error detector
==3167== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==3167== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==3167== Command: ./val
==3167== 

 [a]
==3167== Invalid free() / delete / delete[]
==3167==    at 0x4C270BD: free (vg_replace_malloc.c:366)
==3167==    by 0x40060A: main (valgrind.c:12)
==3167==  Address 0x51b0040 is 0 bytes inside a block of size 1 free'd
==3167==    at 0x4C270BD: free (vg_replace_malloc.c:366)
==3167==    by 0x4005FE: main (valgrind.c:11)
==3167==
==3167==
==3167== HEAP SUMMARY:
==3167==     in use at exit: 0 bytes in 0 blocks
==3167==   total heap usage: 1 allocs, 2 frees, 1 bytes allocated
==3167==
==3167== All heap blocks were freed -- no leaks are possible
==3167==
==3167== For counts of detected and suppressed errors, rerun with: -v
==3167== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

As seen from the output above(lines in bold), the tool detects that we have called free twice on the same pointer.

In this article, we concentrated on memory management framework Valgrind and used the tool memcheck (provided by this framework) to describe how it makes life easy for a developer working close to memory. This tool can detect many memory related problems that are very hard to find manually.

Valgrind is an extremely powerful tool for debugging and
profiling programs written in C or C++. Valgrind has many builtin tools for
various operations, such as checking memory errors, memory profiling, and
profiling CPU branch predictions. In this post I’ll run through the basics of
the default tool memory checking tool, called memcheck. The Valgrind memory
checker is capable of detecting many kinds of memory leaks, access to
uninitialized memory, and out-of-bounds array indexes.

How Valgrind Works

Unlike many other similar tools, Valgrind does not require the program it is
checking to be compiled or linked specially. You can use Valgrind with any
program.

Valgrind works by doing a just-in-time (JIT) translation of the input program
into an equivalent version that has additional checking. For the memcheck tool,
this means it literally looks at the x86 code in the executable, and detects
what instructions represent memory accesses. These instructions are sandboxed,
so that it can trap accesses to uninitialized memory (even if those accesses do
not cause a page fault or segmentation fault). The memcheck tool also has
special knowledge of routines like malloc() and free(), so it can track what
memory is still «reachable» when the program terminates.

The design of Valgrind means that there is no penalty for running instructions
that do not touch main memory (or that are provably already checked). This is
pretty good, although in practice instructions touching main memory are pretty
common. After all, 64-bit x86 systems only have 16 general purpose registers. In
my experience it’s typical for the Valgrind memory checker to slow programs down
by about 10x. This is usually fast enough for development work, although you
wouldn’t want to use Valgrind in production.

To get the most effective results out of Valgrind you should compile your
program with debug symbols. This will allow Valgrind to track full call stacks
for memory violations. Of course, when developing your code you should be
compiling your code with debug symbols anyway.

If you’re interested in an extremely technical description of how Valgrind
works, I refer you
to
The Design and Implementation of Valgrind,
written by Julian Seward, the original author of Valgrind.

Debugging A Simple Memory Leak

We’re going to first look at a simple (but incorrect) program that detects if
~/.bashrc exists:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUF_SIZE 1000

int main() {
  char *path = calloc(BUF_SIZE, 1);
  strcat(path, getenv("HOME"));
  strcat(path, "/.bashrc");
  FILE *foo = fopen(path, "r");
  return foo == NULL;
}

Here are the bugs I see in this program:

  • The program does not check if calloc() returns NULL
  • The unsafe function strcat() is used, instead of strncat()
  • The fopen() call does not have a corresponding fclose()
  • The calloc() call does not have a corresponding free()

Since I’m pedantic, I’ll also note that using getenv() in this way isn’t
strictly correct. A correct program should get the user’s home directory from
/etc/passwd
using getpwent()
or fgetpwent(). The
version here is given for brevity.

Valgrind can detect the errors noted above that are related to bad memory
accesses or allocation/deallocation patterns. In the default mode, here’s what
we see:

$ valgrind ./a.out
==22633== Memcheck, a memory error detector
==22633== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==22633== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==22633== Command: ./a.out
==22633==
==22633==
==22633== HEAP SUMMARY:
==22633==     in use at exit: 1,552 bytes in 2 blocks
==22633==   total heap usage: 2 allocs, 0 frees, 1,552 bytes allocated
==22633==
==22633== LEAK SUMMARY:
==22633==    definitely lost: 1,000 bytes in 1 blocks
==22633==    indirectly lost: 0 bytes in 0 blocks
==22633==      possibly lost: 0 bytes in 0 blocks
==22633==    still reachable: 552 bytes in 1 blocks
==22633==         suppressed: 0 bytes in 0 blocks
==22633== Rerun with --leak-check=full to see details of leaked memory
==22633==
==22633== For counts of detected and suppressed errors, rerun with: -v
==22633== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Here Valgrind is telling us it thinks there are still 1,552 bytes from two
allocations on the heap when the program terminates. That means there are two
memory leaks. Valgrind knows that 1,000 of those bytes are «definitely lost»,
and 552 bytes are «still reachable».

As the output says, we should run with --leak-check=full to get a full error
report. Actually we need a few more options; the full invocation should be:

$ valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all ./a.out
==22679== Memcheck, a memory error detector
==22679== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==22679== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==22679== Command: ./a.out
==22679==
==22679==
==22679== HEAP SUMMARY:
==22679==     in use at exit: 1,552 bytes in 2 blocks
==22679==   total heap usage: 2 allocs, 0 frees, 1,552 bytes allocated
==22679==
==22679== 552 bytes in 1 blocks are still reachable in loss record 1 of 2
==22679==    at 0x4C2DB9D: malloc (vg_replace_malloc.c:299)
==22679==    by 0x4EA905C: __fopen_internal (in /usr/lib64/libc-2.24.so)
==22679==    by 0x400657: main (fopen.c:11)
==22679==
==22679== 1,000 bytes in 1 blocks are definitely lost in loss record 2 of 2
==22679==    at 0x4C2FA50: calloc (vg_replace_malloc.c:711)
==22679==    by 0x4005EC: main (fopen.c:8)
==22679==
==22679== LEAK SUMMARY:
==22679==    definitely lost: 1,000 bytes in 1 blocks
==22679==    indirectly lost: 0 bytes in 0 blocks
==22679==      possibly lost: 0 bytes in 0 blocks
==22679==    still reachable: 552 bytes in 1 blocks
==22679==         suppressed: 0 bytes in 0 blocks
==22679==
==22679== For counts of detected and suppressed errors, rerun with: -v
==22679== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

Great, now we know where the memory leaks come from. Valgrind tells us that the
552 still reachable bytes were allocated from line 11 which called
__fopen_internal, which called malloc. It also tells us that the 1,000
definitely lost bytes come from line 8 which calls calloc.

We can fix those with this diff:

--- fopen1.c    2017-02-20 13:32:20.442466791 -0800
+++ fopen.c    2017-02-20 13:32:23.176399966 -0800
@@ -9,5 +9,7 @@
   strcat(path, getenv("HOME"));
   strcat(path, "/.bashrc");
   FILE *foo = fopen(path, "r");
+  fclose(foo);
+  free(path);
   return foo == NULL;
 }

Now when we run Valgrind it will give us a clean heap summary:

==22786== HEAP SUMMARY:
==22786==     in use at exit: 0 bytes in 0 blocks
==22786==   total heap usage: 2 allocs, 2 frees, 1,552 bytes allocated
==22786==
==22786== All heap blocks were freed -- no leaks are possible

This program still has bugs, as the return values for various methods aren’t
checked. Notably, the return value to calloc() isn’t checked to see if it’s
null. But this is a good start.

«Definitely Lost» vs. «Still Reachable»

Before the leak was fixed, Valgrind said that the memory allocated by calloc()
was «definitely lost», whereas the memory allocated by fopen() was «still
reachable». The Valgrind FAQ
has this explanation for
the difference between «definitely lost» and «still reachable». The short
version is that «definitely lost» memory is just that: definitely an error.
Memory that is «still reachable» is the least worrisome kind of memory leak:
it’s memory that could have been freed, but wasn’t allocated in an unbounded
way.

What’s actually happening here is that when the file is opened, glibc allocates
a structure for the FILE* object. This structure has things like the
underlying file descriptor number, the file name, a read buffer for the file,
and usually a mutex (depending on how glibc was compiled). Since there are a
bounded number of file descriptors you can actually open, there’s also a bounded
amount of memory you can leak in this way before the program would fail to open
new files.

Furthermore, many people don’t care if their program exits with open file
descriptors. For instance, do you close stdin, stdout, and stderr before exiting
your program? Those are also FILE* objects allocated by glibc. No one bothers
to close these before exiting, and it’s not a big deal.

I don’t know the exact heuristics that Valgrind uses to tell which category a
memory leak is in, but my advice is to make a best effort to fix them all, but
to ignore «still reachable» errors if they’re too difficult to fix. In
particular, you may find yourself using certain libraries that trigger «still
reachable» or «possibly lost» memory errors when run through Valgrind. The most
common case is a library that allocates a small, bounded amount of data when
initialized, but exposes no method to deallocate that memory. Take a critical
look at these and Google the errors you find, but remember that perfect is the
enemy of good, and use your programming time productively.

Accessing Uninitialized Memory

C has «undefined behavior» when you read from uninitialized memory, or when you
write to data on the heap outside of a valid range. This is really bad. If
you’re lucky this situation will cause a segfault to occur. If you’re not lucky,
you’ll read invalid data or corrupt the heap.

We can trigger this in our program by setting BUF_SIZE to a small number:

--- fopen1.c    2017-02-20 13:40:10.985125910 -0800
+++ fopen.c    2017-02-20 13:40:13.636064803 -0800
@@ -2,7 +2,7 @@
 #include <stdlib.h>
 #include <string.h>

-#define BUF_SIZE 1000
+#define BUF_SIZE 1

 int main() {
   char *path = calloc(BUF_SIZE, 1);

Now the calloc() call will allocate a buffer that is too small. What’s
interesting is that in practice, if you run this new program with GCC/glibc
you’re unlikely to actually observe an error. This is because the glibc memory
allocator won’t actually ask for just one byte from the operating system: in
practice it will allocate a larger chunk. Thus this program will overrun its
allocated buffer, but probably won’t segfault. In this simple program this may
not be an issue; in a more complicated program this will almost certainly cause
problems, including memory corruption.

Here’s what Valgrind has to say about the new program:

$ valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all ./a.out
==23581== Memcheck, a memory error detector
==23581== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==23581== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==23581== Command: ./a.out
==23581==
==23581== Invalid write of size 1
==23581==    at 0x4C30890: strcat (vg_replace_strmem.c:303)
==23581==    by 0x40069C: main (fopen.c:9)
==23581==  Address 0x5200041 is 0 bytes after a block of size 1 alloc'd
==23581==    at 0x4C2FA50: calloc (vg_replace_malloc.c:711)
==23581==    by 0x40067C: main (fopen.c:8)
==23581==
==23581== Invalid write of size 1
==23581==    at 0x4C3089F: strcat (vg_replace_strmem.c:303)
==23581==    by 0x40069C: main (fopen.c:9)
==23581==  Address 0x520004a is 9 bytes after a block of size 1 alloc'd
==23581==    at 0x4C2FA50: calloc (vg_replace_malloc.c:711)
==23581==    by 0x40067C: main (fopen.c:8)
==23581==
==23581== Invalid read of size 1
==23581==    at 0x4006B3: main (fopen.c:10)
==23581==  Address 0x5200041 is 0 bytes after a block of size 1 alloc'd
==23581==    at 0x4C2FA50: calloc (vg_replace_malloc.c:711)
==23581==    by 0x40067C: main (fopen.c:8)
==23581==
==23581== Invalid write of size 8
==23581==    at 0x4006D0: main (fopen.c:10)
==23581==  Address 0x520004a is 9 bytes after a block of size 1 alloc'd
==23581==    at 0x4C2FA50: calloc (vg_replace_malloc.c:711)
==23581==    by 0x40067C: main (fopen.c:8)
==23581==
==23581== Invalid write of size 1
==23581==    at 0x4006D3: main (fopen.c:10)
==23581==  Address 0x5200052 is 17 bytes after a block of size 1 alloc'd
==23581==    at 0x4C2FA50: calloc (vg_replace_malloc.c:711)
==23581==    by 0x40067C: main (fopen.c:8)
==23581==
==23581== Syscall param open(filename) points to unaddressable byte(s)
==23581==    at 0x4F319B0: __open_nocancel (in /usr/lib64/libc-2.24.so)
==23581==    by 0x4EB5BC2: _IO_file_open (in /usr/lib64/libc-2.24.so)
==23581==    by 0x4EB5E84: _IO_file_fopen@@GLIBC_2.2.5 (in /usr/lib64/libc-2.24.so)
==23581==    by 0x4EA90B3: __fopen_internal (in /usr/lib64/libc-2.24.so)
==23581==    by 0x4006E7: main (fopen.c:11)
==23581==  Address 0x5200041 is 0 bytes after a block of size 1 alloc'd
==23581==    at 0x4C2FA50: calloc (vg_replace_malloc.c:711)
==23581==    by 0x40067C: main (fopen.c:8)
==23581==
==23581==
==23581== HEAP SUMMARY:
==23581==     in use at exit: 0 bytes in 0 blocks
==23581==   total heap usage: 2 allocs, 2 frees, 553 bytes allocated
==23581==
==23581== All heap blocks were freed -- no leaks are possible
==23581==
==23581== For counts of detected and suppressed errors, rerun with: -v
==23581== ERROR SUMMARY: 23 errors from 6 contexts (suppressed: 0 from 0)

What’s interesting here is that even though Valgrind gives us a clean heap
summary («All heap blocks were freed—no leaks are possible»), there are still
a lot of errors. In fact, we see that there are 23 errors from 6 contexts. There
are three types of errors reported:

  • Invalid reads
  • Invalid writes
  • Invalid parameter to syscall «open»

In all of these cases we can see that the calloc() call on line 8 is indicated
as the source of the bad pointer in the stack trace. We can also see what method
did the read or write on that pointer.

Bonus: GCC Builtin Functions

This is probably enough information to fix the bug: the call to calloc() is
indicated as the source of our problems, and in practice that’s probably enough
information to know that the allocation was too small. But let’s look more
closely at the output, because we can see a very interesting thing that GCC is
doing when optimizing this program.

On line 9 of the input program an invalid read and an invalid write are both
indicated. For reference, here’s line 9 of the source program:

strcat(path, getenv("HOME"));  // line 9

And here are the error contexts, as reported by Valgrind:

==23581== Invalid write of size 1
==23581==    at 0x4C30890: strcat (vg_replace_strmem.c:303)
==23581==    by 0x40069C: main (fopen.c:9)
==23581==  Address 0x5200041 is 0 bytes after a block of size 1 alloc'd
==23581==    at 0x4C2FA50: calloc (vg_replace_malloc.c:711)
==23581==    by 0x40067C: main (fopen.c:8)
==23581==
==23581== Invalid write of size 1
==23581==    at 0x4C3089F: strcat (vg_replace_strmem.c:303)
==23581==    by 0x40069C: main (fopen.c:9)
==23581==  Address 0x520004a is 9 bytes after a block of size 1 alloc'd
==23581==    at 0x4C2FA50: calloc (vg_replace_malloc.c:711)
==23581==    by 0x40067C: main (fopen.c:8)

This is saying the original allocation happened through the calloc() call, and
the method doing the bad read/write is the strcat() call on line 9. This is
what we expect.

However, let’s look at the next three contexts, which are all for line 10. For
reference, here’s line 10 of the source program:

strcat(path, "/.bashrc");  // line 10

And here are the error contexts, as reported by Valgrind:

==23581== Invalid read of size 1
==23581==    at 0x4006B3: main (fopen.c:10)
==23581==  Address 0x5200041 is 0 bytes after a block of size 1 alloc'd
==23581==    at 0x4C2FA50: calloc (vg_replace_malloc.c:711)
==23581==    by 0x40067C: main (fopen.c:8)
==23581==
==23581== Invalid write of size 8
==23581==    at 0x4006D0: main (fopen.c:10)
==23581==  Address 0x520004a is 9 bytes after a block of size 1 alloc'd
==23581==    at 0x4C2FA50: calloc (vg_replace_malloc.c:711)
==23581==    by 0x40067C: main (fopen.c:8)
==23581==
==23581== Invalid write of size 1
==23581==    at 0x4006D3: main (fopen.c:10)
==23581==  Address 0x5200052 is 17 bytes after a block of size 1 alloc'd
==23581==    at 0x4C2FA50: calloc (vg_replace_malloc.c:711)
==23581==    by 0x40067C: main (fopen.c:8)

What’s interesting here is that we don’t see strcat() attributed as the
source of the read/write, even though our original program called that method!
What’s going on?

In the strcat() on line 9, the «source» string was dynamic: it comes from
getenv(). So GCC does a regular strcat() here. However, on line 10 the
strcat() call uses a «source» string that is known ahead of time to the
compiler. In this case GCC will actually omit the strcat() call and replace it
with a «builtin» inline version. In other words, GCC has special cased calling
strcat() with a constant source string, and will just inline the logic to do
the concatenation. That’s why Valgrind doesn’t report a call to strcat()!

This behavior can be changed with the flag -fno-builtin, which causes GCC to
avoid this optimization. One reason you might want to know about this is when
debugging a program. If you set a GDB breakpoint on strcat() then you might be
surprised to see that the breakpoint isn’t always executing.

GCC can apply builtin optimizations for many
functions.
Here is a complete list,
from the GCC documentation.

Обучающие статьи Valgrind-memcheck

Valgrund

Эта статья предназначена только для изучения memcheck

Учебная литература:

  • Официальная домашняя страница сайта: http://valgrind.org/

  • Руководство пользователя Valgrind: http://valgrind.org/docs/manual/manual.html

  • Сообщение в блоге CSDN:

https://blog.csdn.net/andylauren/article/details/93189740

https://blog.csdn.net/u010122972/article/details/78214174

Один, Валгринд

Valgrind — это система GPL для отладки и анализа программ Linux.

  1. Автоматическое обнаружение множества ошибок управления памятью и потоков;
  2. Проведите очень подробный анализ производительности;
  3. Valgrind можно использовать в программах без исходного кода.
  4. Valgrind может работать на нескольких популярных платформах, таких как x86 / Linux, AMD64 / Linux и PPC32 / Linux.

Два, набор инструментов Valgrind (набор инструментов)

2.1 Memcheck

Проверка памяти

Memcheck может обнаруживать проблемы с управлением памятью и в основном нацелен на программы C и C ++. При запуске программы под контролем Memcheck все операции чтения и записи в память будут проверяться, а вызовы malloc / new / free / delete будут перехвачены.

  • Доступ к памяти, к которой он не должен обращаться (нераспределенная область, освобожденная область, область в конце блока кучи, недоступная область стека).
  • Опасно использовать неинициализированные значения.
  • Утечка памяти.
  • Плохой выпуск свободных блоков кучи (два выпуска, непревзойденный выпуск).
  • Передайте перекрывающиеся исходный и целевой блоки памяти в memcpy () и связанные функции.

Перекрытие указателя src и dst memcpy и связанных функций.

Memcheck будетСообщить сейчасЭти ошибки и дают ошибкуНомер строки исходного кода, И призыв выйти на эту линиюСтек функцийтрек.

  1. Программа, выполняемая Memcheck, примерно в 10-30 раз медленнее, чем обычно.
  2. Memcheck не выполняет проверки границ глобальных массивов или массивов стека.
  3. Проверьте код во всех поддерживаемых библиотеках динамической компоновки (включая библиотеку C, графическую библиотеку и т. Д.).

2.2 Cachegrind

Cachegrind — это анализатор кеша. Он может выполнять детальное моделирование кешей I1, D1 и L2 в ЦП, поэтому он может точно указать на источник промахов кеша в коде.

2.3 Callgrind

Он предоставляет всю информацию, которую делает Cachegrind, а также другую информацию о графе вызовов.

2.4 Massif

Massif — это анализатор кучи. Включите информацию о том, какие части программы отвечают за выделение большей части памяти.

2.5 Helgrind

Helgrind — это поточный отладчик, который может обнаруживать скачки данных в многопоточных программах.

2.6 и другие инструменты


В-третьих, документ

http://valgrind.org/docs/manual/QuickStart.html

Документация для пользователя: http://valgrind.org/docs/manual/manual-core.html


Четыре, пример выполнения (An Example Run)

4.1 Установка

URL установочного пакета: http://www.valgrind.org/downloads/current.html

 Или же
git clone git://sourceware.org/git/valgrind.git

 Скачать исходный код, скачать документ


tar jxvf valgrind-3.15.0.tar.bz2

cd valgrind-3.15.0/

./configure

make

make install

 // Проверяем успешность установки
valgrind --version

4.2 Написать исходный код

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char *argv[]){    
    // int x = 1;
    int x;
         printf ("x [% d]  n  n", x); // 1, использовать неинициализированные переменные

         char * str1 = malloc (10); // 2, невыделенная память, утечка памяти

    char * str2 = malloc(sizeof(int));
    free(str2);
         // free (str2); // 3, незаконный выпуск


    return 0;
}

4.3 Использование Valgrind

valgrind --tool=memcheck --leak-check=full --show-reachable=yes --trace-children=yes --log-file=out ./test

  • —Tool = значение по умолчанию memcheck, вы можете сделать это без записи; используйте инструмент memcheck (детектор ошибок памяти)
  • —Leak-check = full Показать подробную информацию об ошибке
  • —Show-reachable = yes показать все типы утечек памяти
  • —Trace-children = yes используется при многопоточности, каждый поток будет проверяться
  • —Log-file = вывод журнала вlog Этот файл.

В конце файла журнала будет сводка, которая классифицирует утечки памяти. Всего существует пять категорий:
(1) «определенно потеряно» означает, что ваша программа должна иметь утечку памяти;
(2) «косвенная потеря» означает, что в вашей программе должна быть утечка памяти, и эта утечка связана со структурой указателя.
(3) «возможно потеряно» означает, что в вашей программе должна быть утечка памяти, если только вы не выполняете преднамеренно нетрадиционные операции, такие как указание указателя на выделенный блок памяти. среднее место.
(4) «все еще доступна» означает, что ваша программа может быть в порядке, но не освобождает часть памяти, которая могла быть освобождена. Эта ситуация очень распространена и обычно имеет веские причины.
(5) «подавлено» означает, что некоторая утечка информации была подавлена. Вы можете увидеть некоторые настройки, связанные с подавлением, в файле подавления по умолчанию.

Заявление об авторских правах: эта статья является оригинальной статьей блоггера CSDN «Midnight Worm» и соответствует соглашению об авторских правах CC 4.0 BY-SA.
Исходная ссылка:
https://blog.csdn.net/u010122972/article/details/78214174

4.4 Просмотр отчета об ошибке

Примечание: добавьте, когда вам нужно скомпилировать исходный файл-g

==47085== Memcheck, a memory error detector
==47085== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==47085== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==47085== Command: ./test
==47085== 
==47085== Conditional jump or move depends on uninitialised value(s)
==47085==    at 0x4E998DA: vfprintf (vfprintf.c:1642)
==47085==    by 0x4EA1F25: printf (printf.c:33)
==47085==    by 0x1086FE: main (test1.c:8)
==47085== 
 == 47085 == Использование неинициализированного значения размером 8 // 8 байтов неинициализированного
==47085==    at 0x4E9586B: _itoa_word (_itoa.c:179)
==47085==    by 0x4E98F0D: vfprintf (vfprintf.c:1642)
==47085==    by 0x4EA1F25: printf (printf.c:33)
 == 47085 == by 0x1086FE: main (test1.c: 8) // Конкретное расположение исходного кода
==47085== 
==47085== Conditional jump or move depends on uninitialised value(s)
==47085==    at 0x4E95875: _itoa_word (_itoa.c:179)
==47085==    by 0x4E98F0D: vfprintf (vfprintf.c:1642)
==47085==    by 0x4EA1F25: printf (printf.c:33)
==47085==    by 0x1086FE: main (test1.c:8)
==47085== 
==47085== Conditional jump or move depends on uninitialised value(s)
==47085==    at 0x4E99014: vfprintf (vfprintf.c:1642)
==47085==    by 0x4EA1F25: printf (printf.c:33)
==47085==    by 0x1086FE: main (test1.c:8)
==47085== 
==47085== Conditional jump or move depends on uninitialised value(s)
==47085==    at 0x4E99B4C: vfprintf (vfprintf.c:1642)
==47085==    by 0x4EA1F25: printf (printf.c:33)
==47085==    by 0x1086FE: main (test1.c:8)
==47085== 
x [0]

==47085== 
==47085== HEAP SUMMARY:
==47085==     in use at exit: 10 bytes in 1 blocks
==47085==   total heap usage: 3 allocs, 2 frees, 1,038 bytes allocated
==47085== 
 == 47085 == 10 байтов в 1 блоках определенно потеряны в записи потери 1 из 1 // Память malloc не освобождается
==47085==    at 0x4C2FDFB: malloc (vg_replace_malloc.c:309)
==47085==    by 0x108708: main (test1.c:10)
==47085== 
==47085== LEAK SUMMARY:
==47085==    definitely lost: 10 bytes in 1 blocks
==47085==    indirectly lost: 0 bytes in 0 blocks
==47085==      possibly lost: 0 bytes in 0 blocks
==47085==    still reachable: 0 bytes in 0 blocks
==47085==         suppressed: 0 bytes in 0 blocks
==47085== 
==47085== Use --track-origins=yes to see where uninitialised values come from
==47085== For lists of detected and suppressed errors, rerun with: -s
==47085== ERROR SUMMARY: 6 errors from 6 contexts (suppressed: 0 from 0)
4.5 Пример сообщения об ошибке

Посмотрите на это с другой стороны, сначала посмотрите вниз, затем посмотрите на верх.

==25832== Invalid read of size 4
==25832==    at 0x8048724: BandMatrix::ReSize(int, int, int) (bogon.cpp:45)
==25832==    by 0x80487AF: main (bogon.cpp:66)
==25832==  Address 0xBFFFF74C is not stack'd, malloc'd or free'd
  • 25832 — это идентификатор процесса

  • Программа считывает недопустимое 4-байтовое чтение адреса 0xBFFFF74C. Этот адрес не является допустимым адресом стека и не соответствует какому-либо текущему блоку кучи или недавно освобожденному блоку кучи. Чтение происходит в строке 45 bogon.cpp, вызываемой из строки 66 того же файла.

Процесс обнаружения повторяющихся ошибок — очень дорогостоящий процесс, и если ваша программа генерирует большое количество ошибок, это может привести к значительным накладным расходам производительности.

–error-limit=no

4.10, используйте Valgrind gdbserver и программу отладки GDB

Программы, работающие под Valgrind, не выполняются напрямую процессором. Он работает на синтетическом процессоре, предоставленном Valgrind. Вот почему отладчик не может отлаживать программу при работе на Valgrind.

Используйте программу отладки GDB при использовании инструмента Memcheck

valgrind --vgdb=yes --vgdb-error=0 ./test


 В другой оболочке запустите GDB:

gdb ./test

 // Эта команда находится в потоке valgrind, следуйте подсказкам, чтобы скопировать ее
(gdb) target remote | vgdb

Выйдите из терминала gdb, valgrind выйдет

Пятерка, ядро ​​Валгринда

1. Позвоните в valgrind.
valgrind [valgrind-options] Исходная запущенная команда

Самая важная опция —tool, чтобы решить, какой инструмент Valgrind запускать.

2. Варианты выбора инструмента
--tool=<toolname> [default: memcheck]

имя инструмента, например memcheck, cachegrind, callgrind, helgrind

3. Параметры командной строки Memcheck
--leak-check=<no|summary|yes|full> [default: summary]
	 Если этот параметр включен, поиск утечек памяти после завершения клиентской программы. Если установлено значение «Сводка», это указывает, сколько утечек произошло. Если установлено значение full или yes, каждая утечка будет отображаться подробно и / или засчитываться как ошибка, как указано в параметрах --show-leak-types и --errors-for-leak-types.
	
	
--show-reachable=<yes|no> , --show-possibly-lost=<yes|no>
 Эти параметры предоставляют еще один способ указать тип отображаемой утечки:
	 --show-reachable = no --show-possible-lost = yes эквивалентно --show-leak-types = defined, possible.
	 --show-reachable = no --show-possible-lost = no эквивалентно --show-leak-types = defined.
	 --show-reachable = yes эквивалентно --show-leak-types = all.
	
	
--show-leak-kinds=<set> [default: definite,possible]
	 full указывает тип утечки, который будет отображаться при поиске утечки одним из следующих способов:
	
	 Список из одной или нескольких определенных косвенных возможных достижимостей, разделенных запятыми.
	 all указывает полный набор (все типы утечек). Эквивалентно --show-leak-types = определенно, косвенно, возможно, достижимо.
	 нет пустого множества.


--undef-value-errors=<yes|no> [default: yes]
	 Контролирует, сообщает ли Memcheck об ошибках с неопределенными значениями. Если вы не хотите видеть ошибки неопределенных значений, установите для этого параметра значение no. У этого также есть побочный эффект, заключающийся в некотором ускорении работы Memcheck.


--track-origins=<yes|no> [default: no]
	 Управляет отслеживанием Memcheck источника неинициализированных значений. По умолчанию это не так, что означает, что, хотя он может сказать вам, что неинициализированное значение используется опасным образом, он не может сказать вам, откуда взялось неинициализированное значение. Это часто затрудняет поиск основной проблемы.
	
  • Перед выходом из программыТип утечки памяти установлен:

определенно потерян (абсолютно потерян), косвенно потерян (косвенно потерян), возможно потерян (может быть потерян), все еще доступен (все еще доступен), подавлен (подавлен)

Если указан —leak-check = full, Memcheck предоставит подробную информацию для каждого полностью отсутствующего или, возможно, отсутствующего блока, включая место размещения.

  • Когда указан —leak-check = full, параметр —show-leak-types = управляет набором отображаемых типов утечек.

Значение по умолчанию для отображаемого типа утечки — —show-leak-types = defined, possible.

==46004== Memcheck, a memory error detector
==46004== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==46004== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==46004== Command: ./test
==46004== 
==46004== 
==46004== HEAP SUMMARY:
==46004==     in use at exit: 10 bytes in 1 blocks
==46004==   total heap usage: 1 allocs, 0 frees, 10 bytes allocated
==46004== 
@1==46004== 10 bytes in 1 blocks are definitely lost in loss record 1 of 1
==46004==    at 0x4C2FDFB: malloc (vg_replace_malloc.c:309)
@1==46004==    by 0x108662: main (test1.c:9)
==46004== 
==46004== LEAK SUMMARY:
==46004==    definitely lost: 10 bytes in 1 blocks
==46004==    indirectly lost: 0 bytes in 0 blocks
==46004==      possibly lost: 0 bytes in 0 blocks
==46004==    still reachable: 0 bytes in 0 blocks
==46004==         suppressed: 0 bytes in 0 blocks
==46004== 
==46004== For lists of detected and suppressed errors, rerun with: -s
==46004== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
  • СОДЕРЖАНИЕ УТЕЧКИ в конце программы будет выводиться каждый раз, это не имеет значения …

--leak-check=full Эта опция в основном покажет два@1 Содержание…

--show-leak-kinds=definite,possible Эта опция означает, что подробная информация будет отображать только подробную информацию об определенных и возможных типах утечки памяти.

3.1、–leak-check=full

valgrind —tool=memcheck —leak-check=full ./test

Если указан —leak-check = full, Memcheck предоставит подробную информацию для каждого полностью отсутствующего или, возможно, отсутствующего блока, включая место размещения.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]){
	char * str1 = malloc (10); // 2, невыделенная память, утечка памяти
	
    return 0;
}

Кроме того, это происходит главным образом потому, что эти сообщения об ошибках добавляются, и могут отображаться номера строк и другая информация.

==54477== 10 bytes in 1 blocks are definitely lost in loss record 1 of 1
==54477==    at 0x4C2FDFB: malloc (vg_replace_malloc.c:309)
==54477==    by 0x108662: main (test1.c:9)
3.2、–track-origins=yes

valgrind —tool=memcheck —track-origins=yes ./test

—Tool = memcheck можно опустить, опция по умолчанию

—Track-origins = yes отображать ошибки более подробно

#include <stdio.h>

int main(int argc, char *argv[]){
    
    // int x = 1;
    int x;

         printf ("x [% d]  n  n", x); // Использовать неинициализированные переменные

    return 0;
}


1. Скомпилируйте вашу программу -g, чтобы включить отладочную информацию, чтобы сообщение об ошибке Memcheck содержало точный номер строки.

10. Основные параметры

Подходит для всех инструментов

-h --help     
	 Показать справку по всем параметрам ядра и выбранных инструментов.


--version
	 Показывает номер версии ядра Valgrind.


-v, --verbose
	 Более подробный. Предоставьте дополнительную информацию обо всех аспектах программы,


--trace-children-skip=patt1,patt2,...
	 Эта опция действительна, только если указано --trace-children = yes. Это позволяет пропускать некоторых детей.


--trace-children=<yes|no> [default: no]
	 Если этот параметр включен, Valgrind будет отслеживать дочерние процессы, запущенные системным вызовом exec. Это необходимо для многопроцессорных программ.

	 Обратите внимание, что Valgrind отслеживает дочерний процесс вилки (поскольку вилка создает ту же копию процесса, это сложно сделать, поэтому имя этой опции неверно. Однако большинство дочерних процессов вилки немедленно Вызов exec.
	
	
--vgdb=<no|yes|full> [default: yes]
	 Когда указано --vgdb = yes или --vgdb = full, Valgrind предоставит функцию "gdbserver", что позволяет внешнему отладчику GNU GDB управлять и отлаживать программу во время работы на Valgrind. --vgdb = full вызовет огромные накладные расходы на производительность, но предоставит более точные точки останова и точки наблюдения.

11. Варианты, связанные с ошибками

--xml=<yes|no> [default: no]
	 Если этот параметр включен, важные части вывода (например, сообщения об ошибках инструмента) будут в формате XML вместо обычного текста. Вы также должны использовать --xml-fd, --xml-file или --xml-socket, чтобы указанный XML был отправлен.

--xml-fd=<number> [default: -1, disabled]
	 Указывает, что Valgrind должен отправлять выходные данные XML в указанный файловый дескриптор. Его необходимо использовать вместе с --xml = yes.

--xml-file=<filename>
	 Указывает, что Valgrind должен отправлять выходные данные XML в указанный файл.

--xml-socket=<ip-address:port-number>
	 Указывает, что Valgrind должен отправлять свои выходные XML-данные на указанный порт по указанному IP-адресу.

Добро пожаловать, чтобы подписаться на официальный аккаунт:

Valgrind is an instrumentation framework for building dynamic analysis tools that check C and C++ programs for errors. Memcheck is the default tool Valgrind uses when you don’t ask it for another tool. Other useful tools you can select (using valgrind tool=toolname) are:

  • cachegrind and callgrind, to do cache and call-graph function profiling
  • helgrind and drd, to do thread error and data-race detection
  • massif and dhat, to do dynamic heap usage analysis

Each of these tools deserves an article of its own, but here we will concentrate on Memcheck.

Detecting memory leaks with Valgrind Memcheck

Memcheck tracks all memory reads, writes, allocations, and deallocations in a C or C++ program. The tool can detect many different memory errors. For instance, it detects reads or writes before or after allocated memory blocks. It warns about the use of (partially) undefined values in conditional code or passing such values to system calls. It will also notify you about bad or double deallocation of memory blocks. But for now, we will discuss memory leak detection with Memcheck.

Generating a leak summary

When you run Valgrind on your program without any additional arguments, it produces a summary of the different kinds of leaks it has detected. For example, valgrind ./myprog might produce the following summary:

    LEAK SUMMARY:
      definitely lost: 48 bytes in 1 blocks
      indirectly lost: 24 bytes in 3 blocks
        possibly lost: 0 bytes in 0 blocks
      still reachable: 14 bytes in 1 blocks
           suppressed: 0 bytes in 0 blocks

Memcheck reports leaks in five categories: definitely lost, indirectly lost, possibly lost, still reachable, and suppressed. The first four categories indicate different kinds of memory blocks that weren’t freed before the program ended. If you aren’t interested in specific blocks, you can tell Valgrind not to report them (you’ll see how shortly). The summary also shows you the number of bytes lost and how many blocks they are in, which tells you whether you are losing lots of small allocations, or a few large ones.

The following sections explain each category.

Definitely lost

The first category, definitely lost, is generally the most urgent kind of leak to track down, because there is no way to use or recover that memory. Let’s look at an example of a small program that simply calls output_report a couple of times. That function prints a small banner and a number each time. As we will see, the memory we reserve for the report banner will be definitely lost (multiple times) when the program finishes:

 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>

 char *
 create_banner ()
 {
   const char *user = getenv ("USER");
   size_t len = 1 + 2 * 4 + strlen (user) + 1;
   char *b = malloc (len);
   sprintf (b, "t|** %s **|", user);
   return b;
 }

 void
 output_report (int nr)
 {
   char *banner = create_banner ();
   puts (banner);
   printf ("Number: %dn", nr);
   printf ("n");
 }

 int
 main ()
 {
   for (int i = 1; i <= 3; i++)
     output_report (i);

   return 0;
 }

Compile this code with gcc -Wall -g -o definitely definitely.c and run it under Valgrind, asking for details with valgrind --leak-check=full ./definitely. Now, before the leak summary, Valgrind will show backtraces where the program allocated memory that was ultimately lost:

 42 bytes in 3 blocks are definitely lost in loss record 1 of 1
    at 0x4C29F33: malloc (vg_replace_malloc.c:309)
    by 0x4011C7: create_banner (definitely.c:10)
    by 0x401200: output_report (definitely.c:18)
    by 0x40124C: main (definitely.c:28)

Note that Memcheck found three leaks, which it reports as one loss record because they have identical backtraces. By default, it requires the whole backtrace to be the same in order to consider leaks similar enough to report together. If you want Memcheck to combine more leaks, you can use --leak-resolution=low or --leak-resolution=med to group leaks that have only two or four backtrace entries in common. This is useful if Memcheck reports lots of leaks with slightly different backtraces that you suspect are probably the same issue. You can then concentrate on the record with the highest number of bytes (or blocks) lost.

Still reachable

In the previous example, it is clear we should free banner after use. We could do that at the end of the output_report function by adding free (banner). Then, when running under Valgrind again, it will happily say All heap blocks were freed -- no leaks are possible.

But we are clever and see that the code reuses the same banner for each report. So, we define banner as a static top-level variable in our code and move the create_banner call to the main function, so that create_banneris called only once:

char *banner;

void
output_report (int nr)
{
  puts (banner);
  printf ("Number: %dn", nr);
  printf ("n");
}

int
main
{
  banner = create_banner ();
  for (int i = 1; i <= 3; i++)
    output_report (i);

  return 0;
}

Note how we again forget to call free, this time at the end of main. Now, when running under Valgrind, Memcheck will report still reachable: 14 bytes in 1 blocks and zero bytes lost in any other category.

But the output offers no details of loss records with backtraces for memory blocks that are still reachable, even though we ran with --leak-check=full. This is because Memcheck thinks the error is not very serious. The memory is still reachable, so the program could still be using it. In theory, you could free it at the end of the program, but all memory is freed at the end of the program anyway.

Although still reachable memory isn’t a real issue in theory, you might still want to look into it. You might want to see whether you could free a given block earlier, which might lower memory usage for longer running programs. Or because you really like to see that statementAll heap blocks were freed -- no leaks are possible. To get the details you need, add --show-leak-kinds=reachable or --show-leak-kinds=all to the Valgrind command line (together with --leak-check=full). Now you will also get backtraces showing where still reachable memory blocks were allocated in your program.

Possibly lost

To explore the other categories of leaks, we change our program a little to include some lists of numbers to report. Each report will have a different list of numbers to report. The complete data structure is allocated at the start of the program. And for each set of numbers, we allocate a new block of numbers. To keep things simple (too simple, as Memcheck will point out) we keep just one pointer to the current numbers struct to be printed. Although we create three sets of numbers, we output only two reports:

#include <stdlib.h>
#include <stdio.h>

struct numbers
{
  int n;
  int *nums;
};

int n;
struct numbers *numbers;

void
create_numbers (struct numbers **nrs, int *n)
{
  *n = 3;
  *nrs = malloc ((sizeof (struct numbers) * 3));
  struct numbers *nm = *nrs;
  for (int i = 0; i < 3; i++)
    {
      nm->n = i + 1;
      nm->nums = malloc (sizeof (int) * (i + 1));
      for (int j = 0; j < i + 1; j++)
        nm->nums[j] = i + j;
      nm++;
    }
}

void
output_report ()
{ 
  puts ("numbers"); 
  for (int i = 0; i < numbers->n; i++)
    printf ("Number: %dn", numbers->nums[i]);
  printf ("n");
}

int
main ()
{ 
  create_numbers (&numbers, &n);
  for (int i = 0; i < 2; i++)
    {
      output_report ();
      numbers++;
    }
  return 0;
}

When we compile this program with gcc -Wall -g -o possibly possibly.c and then run it under Valgrind with valgrind --leak-check=full ./possibly, Valgrind reports possibly lost: 72 bytes in 4 blocks. And because we ran with --leak-check=full, it also reports the backtraces:

 24 bytes in 3 blocks are possibly lost in loss record 1 of 2
    at 0x4C29F33: malloc (vg_replace_malloc.c:309)
    by 0x4011C3: create_numbers (possibly.c:22)
    by 0x40128F: main (possibly.c:41)
 
 48 bytes in 1 blocks are possibly lost in loss record 2 of 2
    at 0x4C29F33: malloc (vg_replace_malloc.c:309)
    by 0x401185: create_numbers (possibly.c:17)
    by 0x40128F: main (possibly.c:41)

Memcheck calls this memory possibly lost because it can still see how to access the blocks of memory. The numbers pointer points to the third block of numbers. If we kept some extra information, we could theoretically count backward to the beginning of this block of memory and access the rest of the information, or deallocate the whole block and the other memory it points to.

But Memcheck thinks this is most likely a mistake. And in our example, as in most such cases, Memcheck is right. When walking a data structure without keeping a reference to the structure itself, we can never reuse or free the structure. We should have used the numbers pointer as a base and used an (array) index to pass the current record as output_report (&numbers[i]). Then, Memcheck would have reported the data blocks as still reachable. (There is still a memory leak, but not a severe one, because there is a direct pointer to the memory and it could easily be freed.)

Indirectly lost

In the previous example Memcheck reported a possibly lost block because the numbers pointer was still pointing inside an allocated block. We might be tempted to fix it by simply clearing the pointer after the output_report calls by doing numbers = NULL; to indicate that there is no current numbers list to report. But then we have also just lost the last pointer to our memory data blocks. We should have freed the memory first, but we can’t do it now because we don’t have a pointer to the start of the data structure anymore:

int
main ()
{
  create_numbers (&numbers, &n);
  for (int i = 0; i < 2; i++)
    {
      output_report ();
      numbers++;
    }
  numbers = NULL;
  return 0;
}

Now Memcheck will report the memory as definitely lost. And because the memory block contained pointers to other memory blocks, those blocks are reported as indirectly lost. If we run with --leak-check=full we see a backtrace for the main numbers memory block:

 72 (48 direct, 24 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
    at 0x4C29F33: malloc (vg_replace_malloc.c:309)
    by 0x401185: create_numbers (possibly.c:17)
    by 0x40128F: main (possibly.c:41)

 LEAK SUMMARY:
    definitely lost: 48 bytes in 1 blocks
    indirectly lost: 24 bytes in 3 blocks
      possibly lost: 0 bytes in 0 blocks
    still reachable: 0 bytes in 0 blocks
         suppressed: 0 bytes in 0 blocks

Note how there are no backtraces for the indirectly lost blocks. This is because Memcheck believes you will probably fix that when you fix the definitely lost block. If you do free the definitely lost block, but not the blocks of memory that were indirectly pointed to, next time you run your partially fixed program under Valgrind, Memcheck will report those indirectly lost blocks as definitely lost (and now with a backtrace). So by iteratively fixing the definitely lost memory leaks, you will eventually fix all indirectly lost memory leaks.

If you cannot immediately find the definitely lost block that caused some indirectly lost blocks, it might be informative to see the backtraces for where the indirectly lost blocks were created. When using --leak-check=full you can do that by adding --show-leak-kinds=reachable or --show-leak-kinds=all to the valgrind command line.

Suppressed

By default, Memcheck counts definitely lost and possibly lost blocks as errors with --leak-check=full. It will also show where those blocks were allocated. It doesn’t regard indirectly lost blocks or still reachable lost blocks as errors by default. And it won’t show backtraces for where those still reachable or indirectly lost blocks were allocated, unless explicitly asked to  do so with --show-leak-kinds=all.

Indirectly lost blocks will disappear (or turn into definitely lost blocks) when you resolve the definitely lost issues. Without definitely lost blocks, there can be no indirectly lost blocks. For reachable blocks, it might still make sense to see whether you can deallocate them early, in order to lower memory usage of your program. Or explicitly free them at the end of your program to make sure all memory is really accounted for and cleaned up.

But there might be reasons for not fixing all memory leaks. They might occur in a library you are using that cannot easily be replaced. Or you might be convinced that a possibly lost block isn’t really an error. If, in the original definitely lost example, you decide not to fix the issue and to keep the memory leak, you might want to generate a suppression so Memcheck won’t complain about this particular block again. You can do this easily by running valgrind --leak-check=full --gen-suppressions=all ./definitely which generates an example suppression:

{
   insert_a_suppression_name_here
   Memcheck:Leak
   match-leak-kinds: definite
   fun:malloc
   fun:create_banner
   fun:output_report
   fun:main
}

You can put that into a file (say, local.supp), replacing insert_a_suppression_name_here with something descriptive such as small leak in create_banner. Now, when you run valgrind --suppressions=./local.supp --leak-check=full ./definitely, the leak will be suppressed:

 LEAK SUMMARY:
    definitely lost: 0 bytes in 0 blocks
    indirectly lost: 0 bytes in 0 blocks
      possibly lost: 0 bytes in 0 blocks
    still reachable: 0 bytes in 0 blocks
         suppressed: 42 bytes in 3 blocks

There won’t be any more output for any of the suppressed blocks. But if you want to see which suppressions were used, you can add --show-error-list=yes (or -s) to the valgrind command line. That option makes Valgrind show the suppression name, suppression file, line number, and how many bytes and blocks were suppressed by that suppression rule:

used_suppression:
  1 small leak in create_banner ./local.supp:2 suppressed: 42 bytes in 3 blocks

Test suite integration

When you have resolved all memory leak issues, or when you have suppressions for those you don’t care about, you might want to integrate Valgrind into your test suite to catch any new memory leaks early. If you use --error-exitcode=<number>, Valgrind will change the program’s exit code to the given number when an error (memory leak) is detected. You can also use --quiet (or -q) to make Valgrind silent, so that it doesn’t interfere with the normal stdout and stderr of the program, except for error output, so that you can compare the program output as usual.

Remember that by default Memcheck regards only definitely lost and possibly lost memory blocks as errors. You can change that by using --errors-for-leak-kinds=set. If you are interested in getting an error only for definitely lost blocks, you can use --errors-for-leak-kinds=definite. When your test programs always free all memory blocks, including still reachable blocks, you can use --errors-for-leak-kinds=definite,possibly,reachable or --errors-for-leak-kinds=all. Note that --errors-for-leak-kinds=set, which works together with --error-exitcode=number and the above mentioned --show-leak-kinds=set option, which determines which backtraces to show, are independent. But in general you will want them to be the same, so that you will always get a backtrace for a memory error.

So, a good way to run your tests is valgrind -q --error-exitcode=99 --leak-check=full ./testprog. If you have any local suppressions, you can add --suppressions=local.supp. And if you really want all your test cases to be totally free from any kind of memory leak, add --show-leak-kinds=all --errors-for-leak-kinds=all.

Last updated:
April 22, 2021

Valgrind is a very useful debug tool, which happens to be already installed on EPITECH’s dump.

Introduction¶

What is Valgrind ?¶

Valgrind is an “instrumentation framework for building dynamic analysis tools”, according to Valgrind’s official documentation.

Valgrind comes with a bunch of tools, but in this page we will only focus on one of those tools : Memcheck.

Memcheck is a memory error detector. As such, it will detect and show you every memory error your code produces.
It will also show you your program’s memory leaks.

How to use it ?¶

To use Valgrind to debug your program, you can simply add Valgrind in front of your program’s name and arguments. It should look like this

$ valgrind [valgrind's options] ./program [program's arguments]

Valgrind will now lauch your program and report any error it detects.

Valgrind’s messages¶

Warning

Valgrind will give you more information about where your errors come from if your code has been compiled using GCC’s -g flag.

Invalid read/write¶

One of the most common errors you will encounter are invalid reads or writes.

Invalid write¶

First, let’s write a simple C program.

int main(void)
{
        char *str = malloc(sizeof(char) * 10);
        int i = 0;

        while (i < 15) {
                str[i] = '';
                i = i + 1;
        }
        free(str);
        return (0);
}

Yes, this code is absolutely useless, but still, let’s compile it then run it with valgrind.

$ gcc main.c -g
$ valgrind ./a.out
==18332== Memcheck, a memory error detector
==18332== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==18332== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==18332== Command: ./a.out
==18332==
==18332== Invalid write of size 1
==18332==    at 0x400553: main (test.c:7)
==18332==  Address 0x521004a is 0 bytes after a block of size 10 alloc'd
==18332==    at 0x4C2EB6B: malloc (vg_replace_malloc.c:299)
==18332==    by 0x400538: main (test.c:3)
==18332==
==18332==
==18332== HEAP SUMMARY:
==18332==     in use at exit: 0 bytes in 0 blocks
==18332==   total heap usage: 1 allocs, 1 frees, 10 bytes allocated
==18332==
==18332== All heap blocks were free'd -- no leaks are possible
==18332==
==18332== For counts of detected and suppressed errors, rerun with: -v
==18332== ERROR SUMMARY: 5 errors from 1 contexts (suppressed: 0 from 0)

So, what happened ? Well, Valgrind detected an invalid write error in our program. But what does it mean ?

“Invalid write” means that our program tries to write data in a memory zone where it shouldn’t.

But Valgrind tells you way more than that. It first tells you the size of the written data, which is 1 bytes, and corresponds to the size of a character.
Then the line at 0x400553: main (test.c:7) tells you at which line your error occured. Line 7, which corresponds to str[i] = ''.

At the line Address 0x521004a is 0 bytes after a block of size 10 alloc'd, it also tells you that the invalid adress is located right after a block of ten bytes allocated.
What this means is that a 10 bytes (so probably 10 characters) long memory zone was allocated, but we tried to write an eleventh byte.

Invalid read¶

This other code will produce a Invalid read error :

int main(void)
{
        int i;
        int *ptr = NULL;

        i = *ptr;
        return (0);
}

If we compile and run this code, Valgrind will produce this error :

==26212== Invalid read of size 4
==26212==    at 0x400497: main (test.c:8)
==26212==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

It means that we tried to read 4 bytes, starting at adress 0x0 (for those of you who don’t know it yet, NULL is actually a pointer to adress 0x0, so we tried to read 4 bytes starting from NULL).

As before, Valgrind also tells us that the error occured at line 8 of our code, which corresponds to this instruction : i = *ptr.

Conditional jumps¶

Let’s create a new C program :

int main(void)
{
        int i;

        if (i == 0) {
                my_printf("Hellon");
        }
        return (0);
}

Valgrind will produce this error :

==28042== Conditional jump or move depends on uninitialised value(s)
==28042==    at 0x4004E3: main (test.c:5)

This message may be a bit harder to understand.

Well, a jump is a computer instruction similar to a goto in C. There are several types of jumps. Some are unconditionnal, meaning the jump will always occur. Some other are conditionals,
which means that the jump will be taken if a previous test was successful, and will not otherwise.

In this case, our program had a conditional jump, because one of the values that were test was not initialized, it led to unexpected behaviour. It means that the outcome of the test may change.
For example it could work as intented on your computer, but could fail during the autograder’s tests.

Note

This type of error could happen if you do some tests involving a recently malloc’d block. (Note that malloc will never initialize your data).

Syscall param points to unadressable bytes¶

Here is our program :

int main(void)
{
        int fd = open("test", O_RDONLY);
        char *buff = malloc(sizeof(char) * 3);

        free(buff);
        read(fd, buff, 2);
}

read will try to read at the adress pointed to by buff. But this adress has already been free’d, so Valgrind will show us this error :

==32002== Syscall param read(buf) points to unaddressable byte(s)
==32002==    at 0x4F3B410: __read_nocancel (in /usr/lib64/libc-2.25.so)
==32002==    by 0x400605: main (test.c:11)
==32002==  Address 0x5210040 is 0 bytes inside a block of size 3 free'd
==32002==    at 0x4C2FD18: free (vg_replace_malloc.c:530)
==32002==    by 0x4005EF: main (test.c:10)
==32002==  Block was alloc'd at
==32002==    at 0x4C2EB6B: malloc (vg_replace_malloc.c:299)
==32002==    by 0x4005DF: main (test.c:8)

Here there is a lot of information that will help you debug your code. First, we know that we gave an invalid pointer to a system call, read in our case.

Then Valgrind tells us that this pointer is “0 bytes inside a block of size 3 free’d”. In fact, we allocated a 3 bytes block, then free’d it. “0 bytes inside” means that our pointer
points to the very first byte of this block.

Valgrind tells us where the error occured, where the block was free’d and also where is was malloc’d.

Invalid/mismatched frees¶

Invalid free¶

Another error you may encounter is the “Invalid free” one. It means that we tried to free a pointer that cannot be free’d. Here is an example :

int main(void)
{
        char *buff = malloc(sizeof(char) * 54);

        free(buff);
        free(buff);
        return (0);
}

Yes, I agree, this error is obvious. But it does happen that the same pointer is twice free’d, or that some programmer tries to free something that wasn’t allocated. There are plenty of reasons for
an invalid free to happen. Let’s look at Valgrind’s message :

==755== Invalid free() / delete / delete[] / realloc()
==755==    at 0x4C2FD18: free (vg_replace_malloc.c:530)
==755==    by 0x400554: main (test.c:10)
==755==  Address 0x5210040 is 0 bytes inside a block of size 54 free'd
==755==    at 0x4C2FD18: free (vg_replace_malloc.c:530)
==755==    by 0x400548: main (test.c:9)
==755==  Block was alloc'd at
==755==    at 0x4C2EB6B: malloc (vg_replace_malloc.c:299)
==755==    by 0x400538: main (test.c:7)

Valgrind tells use that there is a problem with a free, a delete, a delete[] or a realloc, but since delete is a C++ instruction, and we’re not allowed to use realloc at EPITECH, you will probably
only use free.

As before, Valgrind tells us that the error occured because we tried to use free on an adress that belongs to an already free’d block.

Mismatched free¶

Another error you can encounter is this one :

==3073== Mismatched free() / delete / delete []
==3073==    at 0x4C2FD18: free (vg_replace_malloc.c:530)
==3073==    by 0x400613: main (in /home/oursin/a.out)
==3073==  Address 0xa09a5d0 is 0 bytes inside a block of size 368 alloc'd
==3073==    at 0x4C2F1CA: operator new(unsigned long) (vg_replace_malloc.c:334)
==3073==    by 0x4E5AB0F: sfSprite_create (in /usr/local/lib/libc_graph_prog.so)
==3073==    by 0x400603: main (in /home/oursin/a.out)

Here, I created a CSFML sprite using sfSprite_create, then I tried to free this sprite, resulting in this error.

In fact, sfSprite_create does allocate some memory, but it does not use our dear friend malloc, but it’s C++ brother, new.
And the problem is that something that has been allocated using new must be free’d using delete, not free. As delete does not exist in C, you should use CSFML’s sfSprite_destroy function.

Fishy values¶

The last type of error you may see is this one :

==29010== Argument 'size' of function malloc has a fishy (possibly negative) value: -1
==29010==    at 0x4C2EB6B: malloc (vg_replace_malloc.c:299)
==29010==    by 0x4004EA: main (in /home/oursin/a.out)

It simply means that you gave a impossible value to a system call. In this case I called malloc with argument -1.

Перейти к содержанию

На чтение 12 мин Опубликовано 16.03.2021

В этом руководстве я расскажу о различных методах и инструментах для обнаружения и поиска утечек памяти с помощью различных процессов в Linux.

Как разработчик, мы часто сталкиваемся с такими сценариями, когда httpd apache, java начинают потреблять большой объем памяти, что приводит к ситуациям OOM (Out Of memory).

Как отключить Out of memory или oom-killer в CentOS / RHEL

Так что всегда полезно следить за использованием памяти критически важным процессом.

Я работаю с приложением, которое требует большого объема памяти, поэтому моя работа – убедиться, что другие процессы не занимают память без надобности.

В этом процессе я использую различные инструменты в для обнаружения утечек памяти и затем сообщаю об этом ответственным админам.

Содержание

  1. Что такое утечка памяти?
  2. 1. Memwatch
  3. 2. Valgrind
  4. 3. Memleax
  5. 4. Сбор дампа ядра
  6. 5. Как определить утечку памяти с помощью стандартных инструментов Linux
  7. Заключение

Что такое утечка памяти?

  • Память выделяется по запросу – с помощью malloc () или одного из его вариантов – и память освобождается, когда она больше не нужна.
  • Утечка памяти происходит, когда память выделяется, но не освобождается, когда она больше не нужна.
  • Утечки, очевидно, могут быть вызваны malloc () без соответствующего free (), но утечки также могут быть вызваны непреднамеренно, если указатель на динамически выделяемую память удален, потерян или перезаписан.
  • Переполнение буфера, вызванное записью после конца блока выделенной памяти, часто приводит к повреждению памяти.
  • Утечка памяти ни в коем случае не уникальна для встроенных систем, но она становится проблемой отчасти потому, что у целевых систем не так много памяти, а отчасти потому, что они часто работают в течение длительных периодов времени без перезагрузки, позволяя утечкам становиться еще больше.
  • Независимо от основной причины ошибки управления памятью могут иметь неожиданные и даже разрушительные последствия для поведения приложений и системы. При сокращении доступной памяти процессы и целые системы могут остановиться, а повреждение памяти часто приводит к неожиданным сбоям.

1. Memwatch

  • MEMWATCH, написанный Йоханом Линдом, представляет собой средство обнаружения ошибок памяти с открытым исходным кодом.
  • Его можно скачать с https://sourceforge.net/projects/memwatch.
  • Просто добавив файл заголовка в свой код и определив MEMWATCH в своей команде gcc, вы можете отслеживать утечки и повреждения памяти в программе.
  • MEMWATCH поддерживает ANSI C; предоставляет журнал результатов; и обнаруживает двойное освобождение, ошибочное освобождение, незафиксированную память, переполнение и недостаточное заполнение и т. д.

Я скачал и извлек memwatch на свой Linux-сервер, как вы можете видеть на скриншоте:

Затем, прежде чем мы скомпилируем программное обеспечение, мы должны прокомментировать приведенную ниже строку из test.c, которая является частью архива memwatch.

Пожалуйста, не спамьте и никого не оскорбляйте.

Это поле для комментариев, а не спамбокс.

Рекламные ссылки не индексируются!

Valgrind is a dynamic analysis tool which detects memory errors and memory leaks. It is spiritually the predecessor of modern debugging tools like AddressSanitizer and LeakSanitizer, but remains relevant for debugging applications today because of its thoroughness and ease of setup (no need to recompile applications). They cover similar but not identical usecases [1].

Installation

For better support for Valgrind in system applications, consider enabling USE=valgrind. For example, this will make dev-lang/python detect when Valgrind is in use and switch allocators from its internal pymalloc to valgrind’s, giving far better output.

USE flags

USE flags for
dev-util/valgrind

An open-source memory debugger for GNU/Linux

mpi Add MPI (Message Passing Interface) layer to the apps that support it

Emerge

root #emerge --ask dev-util/valgrind

Configuration

Environment variables

  • VALGRIND_OPTS

Files

  • ~/.valgrindrc — Local (per user) configuration file.
  • ./.valgrindrc — Local (per project/directory) configuration file.

Usage

Valgrind is actually a suite of tools, but for many people, «Valgrind» is synonymous with the default tool memcheck. The following tools are available, which can be selected with valgrind —tool=name:

  • cachegrind (cache and branch-prediction profiler)
  • callgrind (call-graph generating cache and branch prediction profiler
  • dhat (dynamic heap analysis tool)
  • drd (thread safety analysis)
  • helgrind (thread error detector)
  • lackey (example tool, can be used to analyze a specific function)
  • massif (heap memory profiler)
  • memcheck (memory error detector)

Using Valgrind with applications is easy, simply run valgrind /path/to/application. No recompilation is needed!

For example, to run Valgrind on uptime:

user $valgrind uptime

==3064010== Memcheck, a memory error detector
==3064010== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
==3064010== Using Valgrind-3.20.0 and LibVEX; rerun with -h for copyright info
==3064010== Command: uptime
==3064010==
 03:35:26 up 4 days,  6:58,  1 user,  load average: 0.15, 2.26, 10.93
==3064010==
==3064010== HEAP SUMMARY:
==3064010==     in use at exit: 0 bytes in 0 blocks
==3064010==   total heap usage: 57 allocs, 57 frees, 31,824 bytes allocated
==3064010==
==3064010== All heap blocks were freed -- no leaks are possible
==3064010==
==3064010== For lists of detected and suppressed errors, rerun with: -s
==3064010== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

The output states that uptime ran successfully with no detected memory leaks and no memory safety issues (no out-of-bounds access, etc).

Invocation

user $valgrind --help

usage: valgrind [options] prog-and-args

  tool-selection option, with default in [ ]:
    --tool=<name>             use the Valgrind tool named <name> [memcheck]

  basic user options for all Valgrind tools, with defaults in [ ]:
    -h --help                 show this message
    --help-debug              show this message, plus debugging options
    --help-dyn-options        show the dynamically changeable options
    --version                 show version
    -q --quiet                run silently; only print error msgs
    -v --verbose              be more verbose -- show misc extra info
    --trace-children=no|yes   Valgrind-ise child processes (follow execve)? [no]
    --trace-children-skip=patt1,patt2,...    specifies a list of executables
                              that --trace-children=yes should not trace into
    --trace-children-skip-by-arg=patt1,patt2,...   same as --trace-children-skip=
                              but check the argv[] entries for children, rather
                              than the exe name, to make a follow/no-follow decision
    --child-silent-after-fork=no|yes omit child output between fork & exec? [no]
    --vgdb=no|yes|full        activate gdbserver? [yes]
                              full is slower but provides precise watchpoint/step
    --vgdb-error=<number>     invoke gdbserver after <number> errors [999999999]
                              to get started quickly, use --vgdb-error=0
                              and follow the on-screen directions
    --vgdb-stop-at=event1,event2,... invoke gdbserver for given events [none]
         where event is one of:
           startup exit abexit valgrindabexit all none
    --track-fds=no|yes|all    track open file descriptors? [no]
                              all includes reporting stdin, stdout and stderr
    --time-stamp=no|yes       add timestamps to log messages? [no]
    --log-fd=<number>         log messages to file descriptor [2=stderr]
    --log-file=<file>         log messages to <file>
    --log-socket=ipaddr:port  log messages to socket ipaddr:port
    --enable-debuginfod=no|yes query debuginfod servers for missing
                              debuginfo [yes]

  user options for Valgrind tools that report errors:
    --xml=yes                 emit error output in XML (some tools only)
    --xml-fd=<number>         XML output to file descriptor
    --xml-file=<file>         XML output to <file>
    --xml-socket=ipaddr:port  XML output to socket ipaddr:port
    --xml-user-comment=STR    copy STR verbatim into XML output
    --demangle=no|yes         automatically demangle C++ names? [yes]
    --num-callers=<number>    show <number> callers in stack traces [12]
    --error-limit=no|yes      stop showing new errors if too many? [yes]
    --exit-on-first-error=no|yes exit code on the first error found? [no]
    --error-exitcode=<number> exit code to return if errors found [0=disable]
    --error-markers=<begin>,<end> add lines with begin/end markers before/after
                              each error output in plain text mode [none]
    --show-error-list=no|yes  show detected errors list and
                              suppression counts at exit [no]
    -s                        same as --show-error-list=yes
    --keep-debuginfo=no|yes   Keep symbols etc for unloaded code [no]
                              This allows saved stack traces (e.g. memory leaks)
                              to include file/line info for code that has been
                              dlclose'd (or similar)
    --show-below-main=no|yes  continue stack traces below main() [no]
    --default-suppressions=yes|no
                              load default suppressions [yes]
    --suppressions=<filename> suppress errors described in <filename>
    --gen-suppressions=no|yes|all    print suppressions for errors? [no]
    --input-fd=<number>       file descriptor for input [0=stdin]
    --dsymutil=no|yes         run dsymutil on Mac OS X when helpful? [yes]
    --max-stackframe=<number> assume stack switch for SP changes larger
                              than <number> bytes [2000000]
    --main-stacksize=<number> set size of main thread's stack (in bytes)
                              [min(max(current 'ulimit' value,1MB),16MB)]

  user options for Valgrind tools that replace malloc:
    --alignment=<number>      set minimum alignment of heap allocations [16]
    --redzone-size=<number>   set minimum size of redzones added before/after
                              heap blocks (in bytes). [16]
    --xtree-memory=none|allocs|full   profile heap memory in an xtree [none]
                              and produces a report at the end of the execution
                              none: no profiling, allocs: current allocated
                              size/blocks, full: profile current and cumulative
                              allocated size/blocks and freed size/blocks.
    --xtree-memory-file=<file>   xtree memory report file [xtmemory.kcg.%p]

  uncommon user options for all Valgrind tools:
    --fullpath-after=         (with nothing after the '=')
                              show full source paths in call stacks
    --fullpath-after=string   like --fullpath-after=, but only show the
                              part of the path after 'string'.  Allows removal
                              of path prefixes.  Use this flag multiple times
                              to specify a set of prefixes to remove.
    --extra-debuginfo-path=path    absolute path to search for additional
                              debug symbols, in addition to existing default
                              well known search paths.
    --debuginfo-server=ipaddr:port    also query this server
                              (valgrind-di-server) for debug symbols
    --allow-mismatched-debuginfo=no|yes  [no]
                              for the above two flags only, accept debuginfo
                              objects that don't "match" the main object
    --smc-check=none|stack|all|all-non-file [all-non-file]
                              checks for self-modifying code: none, only for
                              code found in stacks, for all code, or for all
                              code except that from file-backed mappings
    --read-inline-info=yes|no read debug info about inlined function calls
                              and use it to do better stack traces.
                              [yes] on Linux/Android/Solaris for the tools
                              Memcheck/Massif/Helgrind/DRD only.
                              [no] for all other tools and platforms.
    --read-var-info=yes|no    read debug info on stack and global variables
                              and use it to print better error messages in
                              tools that make use of it (Memcheck, Helgrind,
                              DRD) [no]
    --vgdb-poll=<number>      gdbserver poll max every <number> basic blocks [5000]
    --vgdb-shadow-registers=no|yes   let gdb see the shadow registers [no]
    --vgdb-prefix=<prefix>    prefix for vgdb FIFOs [/tmp/vgdb-pipe]
    --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]
    --run-cxx-freeres=no|yes  free up libstdc++ memory at exit on Linux
                              and Solaris? [yes]
    --sim-hints=hint1,hint2,...  activate unusual sim behaviours [none]
         where hint is one of:
           lax-ioctls lax-doors fuse-compatible enable-outer
           no-inner-prefix no-nptl-pthread-stackcache fallback-llsc none
    --fair-sched=no|yes|try   schedule threads fairly on multicore systems [no]
    --kernel-variant=variant1,variant2,...
         handle non-standard kernel variants [none]
         where variant is one of:
           bproc android-no-hw-tls
           android-gpu-sgx5xx android-gpu-adreno3xx none
    --merge-recursive-frames=<number>  merge frames between identical
           program counters in max <number> frames) [0]
    --num-transtab-sectors=<number> size of translated code cache [32]
           more sectors may increase performance, but use more memory.
    --avg-transtab-entry-size=<number> avg size in bytes of a translated
           basic block [0, meaning use tool provided default]
    --aspace-minaddr=0xPP     avoid mapping memory below 0xPP [guessed]
    --valgrind-stacksize=<number> size of valgrind (host) thread's stack
                               (in bytes) [1048576]
    --show-emwarns=no|yes     show warnings about emulation limits? [no]
    --require-text-symbol=:sonamepattern:symbolpattern    abort run if the
                              stated shared object doesn't have the stated
                              text symbol.  Patterns can contain ? and *.
    --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname
              specify patterns for function wrapping or replacement.
              To use a non-libc malloc library that is
                  in the main exe:  --soname-synonyms=somalloc=NONE
                  in libxyzzy.so:   --soname-synonyms=somalloc=libxyzzy.so
    --sigill-diagnostics=yes|no  warn about illegal instructions? [yes]
    --unw-stack-scan-thresh=<number>   Enable stack-scan unwind if fewer
                  than <number> good frames found  [0, meaning "disabled"]
                  NOTE: stack scanning is only available on arm-linux.
    --unw-stack-scan-frames=<number>   Max number of frames that can be
                  recovered by stack scanning [5]
    --resync-filter=no|yes|verbose [yes on MacOS, no on other OSes]
              attempt to avoid expensive address-space-resync operations
    --max-threads=<number>    maximum number of threads that valgrind can
                              handle [500]

  user options for Memcheck:
    --leak-check=no|summary|full     search for memory leaks at exit?  [summary]
    --leak-resolution=low|med|high   differentiation of leak stack traces [high]
    --show-leak-kinds=kind1,kind2,.. which leak kinds to show?
                                            [definite,possible]
    --errors-for-leak-kinds=kind1,kind2,..  which leak kinds are errors?
                                            [definite,possible]
        where kind is one of:
          definite indirect possible reachable all none
    --leak-check-heuristics=heur1,heur2,... which heuristics to use for
        improving leak search false positive [all]
        where heur is one of:
          stdstring length64 newarray multipleinheritance all none
    --show-reachable=yes             same as --show-leak-kinds=all
    --show-reachable=no --show-possibly-lost=yes
                                     same as --show-leak-kinds=definite,possible
    --show-reachable=no --show-possibly-lost=no
                                     same as --show-leak-kinds=definite
    --xtree-leak=no|yes              output leak result in xtree format? [no]
    --xtree-leak-file=<file>         xtree leak report file [xtleak.kcg.%p]
    --undef-value-errors=no|yes      check for undefined value errors [yes]
    --track-origins=no|yes           show origins of undefined values? [no]
    --partial-loads-ok=no|yes        too hard to explain here; see manual [yes]
    --expensive-definedness-checks=no|auto|yes
                                     Use extra-precise definedness tracking [auto]
    --freelist-vol=<number>          volume of freed blocks queue     [20000000]
    --freelist-big-blocks=<number>   releases first blocks with size>= [1000000]
    --workaround-gcc296-bugs=no|yes  self explanatory [no].  Deprecated.
                                     Use --ignore-range-below-sp instead.
    --ignore-ranges=0xPP-0xQQ[,0xRR-0xSS]   assume given addresses are OK
    --ignore-range-below-sp=<number>-<number>  do not report errors for
                                     accesses at the given offsets below SP
    --malloc-fill=<hexnumber>        fill malloc'd areas with given value
    --free-fill=<hexnumber>          fill free'd areas with given value
    --keep-stacktraces=alloc|free|alloc-and-free|alloc-then-free|none
        stack trace(s) to keep for malloc'd/free'd areas       [alloc-and-free]
    --show-mismatched-frees=no|yes   show frees that don't match the allocator? [yes]

  Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc

  Memcheck is Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
  Valgrind is Copyright (C) 2000-2017, and GNU GPL'd, by Julian Seward et al.
  LibVEX is Copyright (C) 2004-2017, and GNU GPL'd, by OpenWorks LLP et al.

  Bug reports, feedback, admiration, abuse, etc, to: www.valgrind.org.

Troubleshooting

Valgrind often needs debug information of the C library to perform function redirection. For this, create the package debug environment described above and apply it for sys-libs/glibc (or sys-libs/musl as needed).

First, debugedit should be installed:

root #emerge --ask dev-util/debugedit

Configure Portage to build selected packages with (enhanced) debugging symbols (-ggdb3) and not to strip them:

CFLAGS="${CFLAGS} -ggdb3"
CXXFLAGS="${CXXFLAGS} -ggdb3"
FEATURES="${FEATURES} splitdebug compressdebug -nostrip"
FEATURES="${FEATURES} installsources"

Enable these settings for the required software:

sys-libs/glibc debugsyms installsources

Remember to re-emerge the libc after setting the needed package.env variables:

root #emerge --ask --oneshot sys-libs/glibc

To get meaningful backtraces, users may need to build more packages (such as dependencies of the software being debugged) with the above environment. For local projects, programs should be built with -Og -ggdb3.

Refuses to launch with strlen error

It is possible that Valgrind refuses to launch with an error like so:

valgrind:  A must-be-redirected function                        
valgrind:  whose name matches the pattern:      strlen          
valgrind:  in an object with soname matching:   ld-linux-x86-64.so.2 

In this case, add -fno-builtin-strlen to CFLAGS for sys-libs/glibc:

# Needed for Valgrind
CFLAGS="${CFLAGS} -fno-builtin-strlen"
sys-libs/glibc glibc-no-strlen

Removal

Unmerge

root #emerge --ask --depclean --verbose dev-util/valgrind

See also

  • GDB — used to find runtime errors that normally involve memory corruption
  • AddressSanitizer — a compiler feature in GCC and Clang that is able to detect several memory access errors.
  • UndefinedBehaviorSanitizer — a compiler feature in GCC and Clang that is able to detect various forms of undefined behaviour (UB).

External resources

  • Debug memory errors with Valgrind and GDB
  • Valgrind Memcheck: Different ways to lose your memory
  • Twenty years of Valgrind
  • GDB valgrind integration

References


  1. Jan Kratochvil. Memory error checking in C and C++: Comparing Sanitizers and Valgrind, Red Hat Developer Blog, May 5th, 2021. Retrieved on January 26th, 2023.

Понравилась статья? Поделить с друзьями:
  • Memcache connect error
  • Melted face bug witcher 3 как исправить
  • Melservo j4 ошибки
  • Melonloader the long dark ошибка
  • Melonloader the long dark error