下面是简单的代码(包括在100个线程中运行malloc()
/free()
序列),在我尝试运行它时会在任何Windows操作系统上崩溃。
非常感谢您提供的任何帮助。
也许使用一些编译指令可以帮助解决问题?
我们在VS2017 Release/x64中构建可执行文件;在运行几分钟后,可执行文件会在我尝试的任何Windows平台上崩溃。
我也尝试过使用VS2015进行构建,但没有帮助。
同样的代码在Linux上运行良好。
实际上,问题比看起来更严重。在生产环境中,当用户呼叫数量超过某个值时,我们的服务器代码每天会无缘无故地崩溃多次。我们试图找出问题并创建最简单的解决方案来复制这个问题。
VS项目的存档在这里。
VS表示命令行为:
/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"
代码:
#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;
}
new
,错误仍然会发生(实际上它仍然调用相同的_malloc_base
函数)。调用堆栈以ntdll.dll!RtlpLowFragHeapAllocFromContext(); tdll.dll!RtlpAllocateHeapInternal(); ucrtbase.dll!_malloc_base()
结束。 - user7860670