Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dumping contents of lost memory reported by Valgrind

When I run valgrind --leak-check=yes on a program, a few bytes of lost memory are reported. Is it possible to view the contents of this memory (i.e. dump the data that is stored in it)?

like image 719
ondra.cifka Avatar asked Sep 30 '12 17:09

ondra.cifka


People also ask

Can Valgrind detect memory corruption?

Valgrind Memcheck is a tool that detects memory leaks and memory errors. Some of the most difficult C bugs come from mismanagement of memory: allocating the wrong size, using an uninitialized pointer, accessing memory after it was freed, overrunning a buffer, and so on.

Does Valgrind catch all memory leaks?

Detecting memory leaks with Valgrind MemcheckMemcheck 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.

Is Valgrind ever wrong?

Yes, there are false positives with Valgrind, that's why it has suppression files for particular glibc and gcc versions, for example.


1 Answers

You can do that with the last version of Valgrind (3.8.1):

Start your executable activating the gdbserver at startup:

valgrind --vgdb-error=0 ....<your program>

Then in another window, connect a gdb to Valgrind (following the indications given by Valgrind). Then put a breakpoint at a relevant place (e.g. at the end of main) and use the gdb

continue

command till the breakpoint is reached. Then do a leak search from gdb:

   monitor leak_check full reachable any

Then list the address(es) of the reachable blocks of the relevant loss record nr

   monitor block_list <loss_record_nr>

You can then use gdb features to examine the memory of the given address(es). Note also the potentially interesting command "who_points_at" if you are searching who has kept a pointer to this memory.

like image 57
ppw Avatar answered Oct 05 '22 23:10

ppw