c++ - 多个线程中的 malloc()/free() 在 Windows 上崩溃

标签 c++ windows multithreading crash malloc

简单代码(下面,malloc()/free() 序列在 100 个线程中运行)在我尝试运行的任何 Windows 操作系统上都会崩溃。

如有任何帮助,我们将不胜感激。

也许使用一些编译器指令会有帮助?

我们在 Release/x64 中构建 VS2017 中的可执行文件;运行几分钟后,可执行文件在我尝试的任何 Windows 平台上崩溃。

我也尝试过使用 VS2015 进行构建,但没有帮助。

相同的代码在 Linux 上运行良好。

实际上,问题比看起来更严重;我们面临这样的情况:我们的服务器代码在生产环境中每天无缘无故崩溃几次(当用户调用的号码超过某个值时)。我们试图确定 问题并创建最简单的解决方案来重现该问题。

VS 项目的存档是 here .

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" 

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;
}

最佳答案

这是 Windows 低碎片堆的问题。它已在 OS build 19041(2020 年 5 月更新)中修复。

关于c++ - 多个线程中的 malloc()/free() 在 Windows 上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48906343/

相关文章:

windows - 通过 .bat 文件打开/关闭应用程序 [Windows]

python - 使用 virtualenv 创建的 python 实例的外部应用程序? ( Windows )

C++ 可运行类

c++ - 写时复制正确用法?

c++ - 如何在 GPU 而不是 CPU 上运行 qt 应用程序

windows - NSIS 自动和静默更新

c++ - 循环数组(队列)迭代器

java - 生产者批量消费;在前一批完成之前,第二批不应到来

c++ - 不同水平位置的进度条布局

c++ - 直接从 RAM C++ 读取字节