Thread-safe memory management

SDL uses internal C functions for memory management.
I use SDL library in my C++ code project and use C++ functions (new, new[], delete, delete[], std::vector::push_back() and etc) for appliction-level dynamycally created objects.
Sometimes I need to create objects in different threads.

Is it thread-safe memory management technique when SDL uses own C functions and I use C++ functions?

When I tried to use at app start point before SDL_Init call

if (SDL_SetMemoryFunctions(std::malloc, std::calloc, std::realloc, std::free) != 0)
    logError("SDL_SetMemoryFunctions error %s", SDL_GetError());

After window closing by pressing “x” window button app raise error


Exactly the same is happening for me. Did you ever solve this?

I think by the time we call SDL_SetMemoryFunctions in main(), SDL has already allocated some memory?

I think SDL_SetMemoryFunctions is useless. There is never a situation where this will work.

Hmm, it looks like our WinMain() does in fact malloc() memory to build out argc/argv, which is not good.

This is a bug (and does not need an API change to fix), but we probably won’t fix this before 2.0.9.


I’d love this to work, but it’s not vital for 2.0.9. Would you like me to raise a bug after 2.0.9 release?

Raise one right now if you have a minute so we don’t forget! :slight_smile:

Is the issue happening with official SDL binaries (which are mingw-compiled)
or does it happen if you build SDL yourself using MSVC?

This happens across the board on Windows (it failed for me on MinGW and VC++ builds), as Ryan’s acknowledged it’s a bug that needs fixing.

Just reported it here

Sam said fix it for 2.0.9, so here you go. :slight_smile:

Please test this if you can!

This is fixed in 2.0.9 now. Tested and working well. I’ve even messed around with garbage collection (freeing up unused game resources, for example) while SDL calls the custom malloc() and it works as expected.

Please note that if you put a chunk counter in, you will get some small chunks (about 2 to 8) leaked by SDL at exit. Sam’s aware and it may or may not be fixed in next release. It’s not a major issue.

1 Like