Categories
Uncategorized

Built-in memory leak detector

I didn’t know this until today but Visual Studio has a built-in memory leak detector. One day out of the blue my game starts to take a long time to shut down and in the output window I see Detected memory leaks! Followed by a bunch of numbers. I looked it up today and after […]

I didn’t know this until today but Visual Studio has a built-in memory leak detector. One day out of the blue my game starts to take a long time to shut down and in the output window I see

Detected memory leaks!

Followed by a bunch of numbers.

I looked it up today and after some research, I found out that the allocator counts memory allocations, and prints out the memory allocation number that caused the leak. I don’t know why in all the time I’ve been programming I’ve never heard about this before but it’s really useful!

This only works if your program state is repeatable (such as on startup) but it works really well from what I’ve seen.

All you have to do is put

#define _CRTDBG_MAP_ALLOC
#include <stdlib .h >
#include < crtdbg .h >

Somewhere at the top of your program.

Then either put at the start

_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

or put

_CrtDumpMemoryLeaks();

at the end.

Lastly, to break at the specified allocation number, call


_CrtSetBreakAlloc(X);

where X is the allocation number.

Alternatively, put this in your watch window:


{,,msvcr80d.dll}_crtBreakAlloc

It should show -1. Change that -1 to the number of the allocation.

For example:


Detected memory leaks!
Dumping objects ->
{614841} normal block at 0x123A7D30, 8 bytes long.
Data: <> 7F 00 00 01 08 E6 CD CD

I put F10 to step one line into my program.

I put {,,msvcr80d.dll}_crtBreakAlloc into the watch window.

I change the -1 to 614841.

I press F5 to run.

It should break when it hits this allocation.

I just fixed 2 leaks in about 5 minutes that I would have never found otherwise and only have 614,841 to go 🙂

2 replies on “Built-in memory leak detector”

Leave a Reply

Your email address will not be published. Required fields are marked *