Suspected memory leak with _beginthread

127 Views Asked by At

So, i have some issues with i suspect a memory leak, in order to test i wrote this small code. By commenting the following line:

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

the code runs well. But when i uncomment it, the program crashed after a couple thousand threads.. When i use try/catch, the program just crashed inside the try function. Anyone who can help me out here?

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

There are 1 best solutions below

6
On

Well, let do some calc. Your t struct has 40020 bytes per instance. You do allocate it 1M times that causes about 40 Gb allocated in total. And this is not all the memory required because each thread is not for free. By default, Windows allocates 1Mb stack per thread that gives you 1 Tb (one terabyte) of memory required just to let the threads live.

So, total memory amount is something like 1040 Gb. Do you really intend that?