Skip to content

Instantly share code, notes, and snippets.

@vaiorabbit
Last active March 27, 2021 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaiorabbit/9c2210da69a0c91c71f20d9dd47caaa5 to your computer and use it in GitHub Desktop.
Save vaiorabbit/9c2210da69a0c91c71f20d9dd47caaa5 to your computer and use it in GitHub Desktop.
SDL memory leak check (tested on v2.0.14)
// Ref.: https://stackoverflow.com/questions/4790564/finding-memory-leaks-in-a-c-application-with-visual-studio
#include "windows.h"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <SDL.h>
class Application
{
public:
static void* Allocate(size_t size)
{
return malloc(size);
}
static void* AllocateArray(size_t count, size_t size)
{
return calloc(count, size);
}
static void* Reallocate(void* ptr, size_t size) {
return realloc(ptr, size);
}
static void Free(void* ptr) {
return free(ptr);
}
Application() = default;
~Application()
{
ReportDifference();
}
void Initialize()
{
_CrtMemCheckpoint(&m_memoryStateInit);
SDL_SetMemoryFunctions(Application::Allocate, Application::AllocateArray, Application::Reallocate, Application::Free);
SDL_Init(0);
}
void Finalize()
{
SDL_Quit();
_CrtMemCheckpoint(&m_memoryStateTerm);
}
private:
void ReportDifference()
{
_CrtMemState memoryStateDiff;
if (_CrtMemDifference(&memoryStateDiff, &m_memoryStateInit, &m_memoryStateTerm))
{
_CrtMemDumpStatistics(&memoryStateDiff);
_CrtDumpMemoryLeaks();
}
}
_CrtMemState m_memoryStateInit;
_CrtMemState m_memoryStateTerm;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
Application app;
app.Initialize();
app.Finalize();
return 0;
}
/*
220 bytes in 2 Normal Blocks.
0 bytes in 0 CRT Blocks.
0 bytes in 0 Ignore Blocks.
0 bytes in 0 Client Blocks.
Largest number used: 283 bytes.
Total allocations: 305 bytes.
Detected memory leaks!
Dumping objects ->
C:\Users\foo\Documents\TLSLeakCheck\TLSLeakCheck.cpp(14) : {97} normal block at 0x000001746C68B3F0, 132 bytes long.
Data: < > 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
C:\Users\foo\Documents\TLSLeakCheck\TLSLeakCheck.cpp(23) : {96} normal block at 0x000001746C68ABA0, 88 bytes long.
Data: < hlt > 05 00 00 00 CD CD CD CD F0 B3 68 6C 74 01 00 00
Object dump complete.
HEAP[TLSLeakCheck.exe]: Invalid address specified to RtlValidateHeap( 000001746C680000, 000001746C660020 )
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment