Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello everyone,

I'm trying to write my first multithreaded program.
I have a thread that looks like this:

C#
UINT TestThread(LPVOID lpData)
{
    while(true){
        // stuff to do (will be serial communication)
        Sleep(500);
    }
    return 0;
}


Which I call from main like this:
AfxBeginThread(TestThread,NULL,THREAD_PRIORITY_NORMAL);


Problem: I get a memory leak during debugging:

Detected memory leaks!
Dumping objects ->
f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\thrdcore.cpp(306) : {108} client block at 0x0039C728, subtype c0, 68 bytes long.
a CWinThread object at $0039C728, 68 bytes long


First time I'm dealing with memory leaks so I googled and found a way to try to "locate" the leak (well ... not much to locate with about 5 lines of code)
following the instructions on http://www.codeguru.com/forum/showthread.php?t=499952[^], using a breakpoint and {,,msvcr90d.dll}_crtBreakAlloc and it points me to the AfxBeginThread Line as source of the problem.

If I don't put a while loop in there, it works fine.
I feel like maybe I misunderstood the concept of how threading is supposed to work :)
Because if I'm conceptually not allowed to put the "while" there, the threading concept kind of looses it's use ... for what I'm trying to do, at least.

Thanks a lot for any answers either explaining how to fix the memory leak problem OR why I'm not allowed to put while(true) in a thread (or maybe both :))

EDIT:
Ok, there seems to be a more fundamental problem. I ALSO get a memory leak if I use.
std::cout << "Starting Thread ..." << std::endl;

Now I'm really lost, really appreciate any help.
Posted
Updated 19-May-11 19:34pm
v4

This is trivial, if you don't terminate a thread properly, all of its internal memory will leak. Terminate properly and it won't be an issue.
 
Share this answer
 
Try sending some data to thread instead of NULL.
 
Share this answer
 
Comments
tschoni 20-May-11 5:16am    
thanks for the tipp, might be safer, but by itself it didn't solve the problem
Ok, following seems to be the explanation:

Nothing to do with loops or cout or whatever is in the thread.
To NOT get a memory leak the thread needs to terminate (return 0;) before the calling threat (main in my case) terminates.

Simple as that.

This statement only based on "observation", so maybe it's not true ... seems reasonable tough.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900