Finding where memory was last freed?
Asked Answered
C

3

4

Very general: Is there an easy way to tell which line of code last freed a block of memory when an access violation occurs?

Less general: My understanding of profilers is that they override the allocation and deallocation processes. If this is true, might they happen to store the line of code that last freed a section of memory so that when it later crashes because of an access violation, you know what freed it last?

Specifics: Windows, ANSI C, using Visual Studio

Chemesh answered 27/3, 2009 at 23:23 Comment(0)
H
7

Yes!

Install the Windows Debugging Tools and use Application Verifier.

  1. File -> Add Application, select your .exe
  2. Under Basics, select Memory and Heaps.
  3. Run the debug build of your program under ntsd (ntsd yourprogram.exe).
  4. Reproduce the bug.

Now when you make the crash happen, you will get additional information in the debugger from AppVerifier. Use !avrf (may take a long time to run (minutes)) and it will try to give you as much useful information as possible.

You can all use the dps command on the memory address to get all the stored stack info (allocation, deallocation, etc).

You can also use the !heap command on the memory address:

0:004> !heap -p -a 0x0C46CFE0

Which will dump information as well.

Further Reading:

Hormonal answered 27/3, 2009 at 23:34 Comment(0)
H
0

Short answer: no.

What you need is a debug malloc. I don't keep up with Windows any longer but there are several about, including this free one.

Update

Looks like Visual Studio C has a built in version. See here

When the application is linked with a debug version of the C run-time libraries, malloc resolves to _malloc_dbg. For more information about how the heap is managed during the debugging process, see The CRT Debug Heap.

... and see here for _malloc_dbg.

Hayne answered 27/3, 2009 at 23:32 Comment(0)
N
-1

No, not unless you provide your own allocators (e.g. by overloading new/delete) to store this information.

What profilers do is highly dependent on what they're profiling. I'm not aware of any profiler that tracks what you're looking for.

Perhaps if you provided more details on your situation people could suggest an alternative means of diagnosing the problem you're encountering.

Nabonidus answered 27/3, 2009 at 23:28 Comment(1)
e.g.= example. In this case use a custom/malloc free in your app, which if memory performance is important you will already have.Nabonidus

© 2022 - 2024 — McMap. All rights reserved.