malloc()/free() in several threads crahes on Windows - what's wrong?

  • Thread starter Thread starter Peter_G1
  • Start date Start date
P

Peter_G1

Guest
Simple code (below, malloc()/free() sequence being run in 100 threads) crashes on any Windows OS I tried it to run.

Any help would be greatly appreciated.

Maybe using some compiler's directive can help?

We build the exe in VS2017 in Release/x64; the executable file crashes on any Windows platform I tried after several minutes of running.

I tried building with VS2015 as well but it doesn't help.

The same code on Linux works fine.

Actually, problem is more serious than it looks; we faced the situation when our server code crashes several times a day in a production environment without any reason (when user calls' number exceeds a certain value). We tried to nail down the issue and created simplest solution that reproduces the problem.

VS says that 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 = thread(task);
}

for (int i = 0; i < MAX_THREADS; i++)
{
some_threads.join();
}

_getch();
return 0;
}

Continue reading...
 
Back
Top