akhil
akhil

Reputation: 732

Memory management during Windows Thread Creation

I need one clarification related to the Windows Threads (WEC7). Consider the following sample code. I would like to know whether any memory leak in the code.

In the code snippet MyThread1 creates memory in the heap and passed to MyThread2 and the allocated memory is cleared there.

DWORD WINAPI MyThread2(LPVOID lpVoid)
{
    int* b = (int*)lpVoid;
    int c = *b;
    free(lpVoid);
    return 0;
}


DWORD WINAPI MyThread1(LPVOID lpVoid)
{
    int count =100;
    while(count)
    {
        int* a = NULL;
        a= (int*)malloc(sizeof(int));
        *a =  count;
        CloseHandle(CreateThread(NULL, 0, MyThread2,(LPVOID)a, 0, NULL));
        count --;
    }
    return 0;
}
int main()
{


    CreateThread(NULL, 0, MyThread1,NULL, 0, NULL);
    // wait here until MyThread1 exits.

    return 0;
}

Upvotes: 0

Views: 182

Answers (2)

David Heffernan
David Heffernan

Reputation: 612954

There's no leak of memory. The calls to malloc are matched by calls to free.

It is possible the some thread 2 instances have not started to run when thread 1 finishes and the program closes. But at that point the system reclaims memory.

You don't call CloseHandle for thread 1, but then I guess this isn't real code. In the real code you would for sure have to capture the handle for thread 1 so you can wait on it.

HANDLE hThread1 = CreateThread(NULL, 0, MyThread1,NULL, 0, NULL);
WaitForSingleObject(hThread1, INFINITE);
CloseHandle(hThread1);

Note that I've adopted your policy of eliding error checking for simplicity of exposition. Of course in real code you'd add error handling for all API calls.

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 596216

The code you have shown will leak if CreateThread() in MyThread1() fails to create a new thread. You are not checking for that condition so MyThread1() can free the memory it allocated. Other than that, since you are allocating memory in one thread and freeing it in another thread, make sure you are using the multi-threaded version of your compiler's RTL.

Upvotes: 2

Related Questions