gpt4 book ai didi

c++ - _beginthread 疑似内存泄漏

转载 作者:行者123 更新时间:2023-11-28 04:44:26 24 4
gpt4 key购买 nike

所以,我有一些问题,我怀疑内存泄漏,为了测试我写了这段小代码。通过注释以下行:

printf("Calc index: %d\n", ArrLength);

代码运行良好。但是当我取消注释时,程序在几千个线程后崩溃了。当我使用 try/catch 时,程序只是在 try 函数内崩溃。谁能帮帮我?

#include "stdafx.h"
#include <process.h>
#include <iostream>
#include <mutex>

#include <windows.h>

using namespace std;

typedef struct {
int StartNode;
int EndNode;
int GangID;
int MemberID;
int ArrLength;
int arr[10000];
}t;
t *arg;
mutex m;

void myFunc(void *param) {
m.lock();

printf("Calculate thread started\n");
t *args = (t*)param;
int StartNode = args->StartNode;
int EndNode = args->EndNode;
int GangID = args->GangID;
int MemberID = args->MemberID;
int ArrLength = args->ArrLength;
printf("Calc index: %d\n", ArrLength);

free(args);

m.unlock();
}

int main()
{
for (int i = 0; i < 1000000; i++)
{
HANDLE handle;
arg = (t *)malloc(sizeof(t));
arg->StartNode = 2;
arg->EndNode = 1;
arg->GangID = 1;
arg->MemberID = 1;
arg->ArrLength = 5;
for (int j = 0; j < 10000; j++)
{
arg->arr[j] = j;
}
handle = (HANDLE)_beginthread(myFunc, 0, (void*)arg);
}
cin.get();
return 0;
}

最佳答案

好吧,让我们做一些计算。您的 t 结构每个实例有 40020 个字节。您确实分配了 1M 次,导致总共分配了大约 40 Gb。而且这还不是所需的全部内存,因为每个线程都不是免费的。默认情况下,Windows 为每个线程分配 1Mb 堆栈,这为您提供了 1 Tb(1 TB)的内存,仅供线程运行。

因此,总内存量约为 1040 Gb。你真的打算那样吗?

关于c++ - _beginthread 疑似内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49561787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com