malloc()/free() in several threads crashes on Windows malloc()/free() in several threads crashes on Windows windows windows

malloc()/free() in several threads crashes on Windows


This is an issue with the Windows Low Fragmentation Heap. It was fixed in OS build 19041 (the May 2020 update).


Nothing in your remarkably small MVCE indicates a programming error, malloc() and free() are supposed to be thread safe and so should the methods invoked on cout. The program is not designed to ever stop, so it appears to be a fine stress test for malloc() in a multi-thread context.

Note however that if malloc() fails, it is questionable to try and report the error to cout, which might make further calls to malloc() for buffering. Reporting the error to cerr or making cout unbuffered is advisable. In any case malloc() failure should not cause a crash, even in the stream methods.

It looks like you found a bug in the runtime library you link to on the VS target platform. It would be interesting to track the memory usage of the program up to the crash. A steady increase in memory usage would indicate some problems in the runtime library too. The program never allocates more than MAX_THREADS blocks of 4K at a time, so the memory use should remain quite low, below 2MB, including the overhead associated with the thread based caches used by modern implementations of malloc().