Matching address of object to address in valgrind leak report

Viewed 53

I purposely introduced a memory leak in my code.

MyClass *classy = new MyClass();
cout << "Address of classy is " << classy << endl;

Assuming I did it right, the program prints out "Address of classy is 0x5b08c80" as the location in memory of the MyClass object created on the heap (as opposed to the pointer itself).

Then, I run the program with valgrind --leak-check=full with the expectation that the same memory address will appear somewhere in the leak report.

==25743== 56 bytes in 1 blocks are definitely lost in loss record 1 of 2
==25743==    at 0x4C2A098: operator new(unsigned long) (vg_replace_malloc.c:333)
==25743==    by 0x405D18: main (test.cpp:222)

As you can see, the address of the MyClass object does not appear in the leak report.

This is not a trivial matter. If this were a more insidious memory leak in a much larger program, I would want to be able to track it down, and matching the address reported by valgrind would be the best way to do it.

Assuming I have correctly identified the line of code causing a memory leak, is there any way I can print out the memory address that will appear in the valgrind report? I am looking to have the same memory address in both places like so:

"Address of classy is 0x123456"

==25743== 56 bytes in 1 blocks are definitely lost in loss record 1 of 2
==25743==    at 0x123456: operator new(unsigned long) (vg_replace_malloc.c:333)
1 Answers

For definitely leaked blocks, it is not very clear to me why the stack trace of the allocation of the leaked block does not give enough information to solve the leak.

For possibly leaked blocks and for still reachable blocks, the address of the block can be used to determine which other blocks still points at the possibly or still reachable blocks.

When you debug your program under valgrind+vgdb, you can report the list of blocks for each loss record. This can e.g. be used to find the reason of possibly lost or still reachable.

See https://valgrind.org/docs/manual/mc-manual.html#mc-manual.monitor-commands e.g. the commands 'monitor block_list' and 'monitor who_points_at'.

This interactive gdb+vgdb way to obtain the addresses and sizes of leaked blocks is the only available leaked block list.

Related