12

Given a double-free error (reported by valgrind), is there a way to find out where the memory was allocated? Valgrind only tells me the location of the deallocation site (i.e. the call to free()), but I would like to know where the memory was allocated.

JesperE
  • 63,317
  • 21
  • 138
  • 197
  • 1
    You could instrument your code in the build you use for Valgrind checks and make sure to take note of allocations and frees. However, with `--error-limit=no --track-origins=yes` I was so far always able to deduce the origin, given the call stacks. – 0xC0000022L Apr 14 '11 at 19:42
  • 1
    I was able to track down this particular problem by using the glibc malloc hooks described in http://www.gnu.org/s/hello/manual/libc/Hooks-for-Malloc.html. Neither `--error-limit=no` or `--track-origins=yes` gave any useful info, but the malloc hooks together with some semi-intelligent guesswork allowed me to figure out the problem. But I guess the question still stands, even if I've solved this problem. – JesperE Apr 15 '11 at 17:35
  • basically I asked some time ago on the mailing list why various kinds of backtracking the way you want it (and I wanted it) are not possible. The reasoning was that there would be way too many false positives and in many cases the results would be very inconclusive. Thus I doubt the feature you want exists as such. Even if that's not the answer you'd like to hear ;) – 0xC0000022L Apr 15 '11 at 19:44
  • This is _not_ a Linux-specific question... The "linux" tag is not appropriate. – Mikhail T. Jan 06 '17 at 01:21

2 Answers2

14

To get Valgrind keep tracks of allocation stack traces, you have to use options:

--track-origins=yes --keep-stacktraces=alloc-and-free

Valgrind will then report allocation stack under Block was alloc'd at section, just after Address ... inside a block of size x free'd alert.

In case your application is large, --error-limit=no --num-callers=40 options may be useful too.

Yves Martin
  • 10,217
  • 2
  • 38
  • 77
1

The first check I would do is verifying that the error is indeed due to a double-free error. Sometimes, running a program (including with valgrind) can show a double-free error while in reality, it's a memory corruption problem (for example a memory overflow).

The best way to check is to apply the advice detailed in the answers : How to track down a double free or corruption error in C++ with gdb.

First of all, you can try to compile your program with flags fsanitize=address -g. This will instrument the memory of the program at runtime to keep track of all allocations, detect overflows, etc.

In any case, if the problem is indeed a double-free, the error message should contain all the necessary information for you to debug the problem.

lgeorget
  • 400
  • 4
  • 13