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

Simple code (below, the malloc() / free() sequence runs in 100 threads) crashes on any Windows OS that I tried to run.

Any help would be greatly appreciated.

Maybe some kind of compiler directive will help?

We are building the executable in VS2017 in Release / x64; The executable crashes on any Windows platform that I tried after a few minutes of work.

I also tried to build with VS2015, but this does not help.

The same code on Linux works fine.

In fact, the problem is more serious than it seems; We are faced with a situation where our server code crashes several times a day in a production environment for no reason (when the number of user calls exceeds a certain value). We tried to nail the problem and created a simple solution that reproduces the problem.

The archive with the VS project is here .

VS says the command line is:

  /Yu"stdafx.h "/ GS / GL / W3 / Gy / Zc: wchar_t / Zi / Gm- / O2 / sdl 
 /Fd"x64\Release\vc140.pdb "/ Zc: inline / fp: precise / D" NDEBUG "
 / D "_CONSOLE" / D "_UNICODE" / D "UNICODE" / errorReport: prompt / WX- / Zc: forScope / Gd
 / Oi / MD / Fa "x64 \ Release \" / EHsc / nologo / Fo "x64 \ Release \" /Fp"x64\Release\MallocTest.pch " 

Code:

 #include "stdafx.h" #include <iostream> #include <thread> #include <conio.h> using namespace std; #define MAX_THREADS 100 void task(void) { while (true) { char *buffer; buffer = (char *)malloc(4096); if (buffer == NULL) { cout << "malloc error" << endl; } free(buffer); } } int main(int argc, char** argv) { thread some_threads[MAX_THREADS]; for (int i = 0; i < MAX_THREADS; i++) { some_threads[i] = thread(task); } for (int i = 0; i < MAX_THREADS; i++) { some_threads[i].join(); } _getch(); return 0; } 
+10
source share
1 answer

Nothing in your surprisingly small MVCE indicates a programming error, it is assumed that malloc() and free() are thread-oriented, as are the methods called in cout . The program is not intended to ever stop, so it looks like a good stress test for malloc() in a multi-threaded context.

However, note that if malloc() fails, it is doubtful to try to report an error in cout , which may lead to further calls to malloc() for buffering. It is advisable to report an error in cerr or make cout unbuffered. In any case, a malloc() failure should not cause a failure, even in stream methods.

It looks like you found a bug in the runtime library that you are referencing from on the target VS platform. It would be interesting to track the memory usage of the program until the crash. The constant increase in memory usage also points to some problems in the runtime library. A program never allocates more than MAX_THREADS blocks of 4 KB at a time, so memory usage should remain fairly low, below 2 MB, including the overhead associated with stream-based caching used in modern malloc() implementations.

+1
source

Source: https://habr.com/ru/post/1275482/


All Articles