[Webinar] Streamline your web hosting managementRegister Today

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 174
  • Last Modified:

Memory leaks with multiple threads


I am writing a multithreaded program that receives connections from a socket within a thread and then creates another "child" thread to handle futher communications on that socket. Then the "father" thread goes back to waiting for more connection attempts. When the "child" thread finishes its operations I close the socket handle, delete dynamic memory, and do an ExitThread. The problem is that everytime this happens the memory is not released. Shouldn't all memory be released after the "child" thread is done. Also, note that up to 60 "child" threads may be created and terminated at the same time so the memory is creeping up very quickly? Does ExitThread unload the threads stack memory automatically?

Please, any help would be appreciated.
  • 2
  • 2
1 Solution
>> ExitThread unload the threads stack memory
>> automatically
yes and other OS thread-related resources

However, from a C++ process you shoudl not use ExitThread() (Or CreateThread())  You should be using _beginthread() and _endthread(). These initialize and clean-up the C++ runtime library for the thread.  (Thus _endthread() may free memory.)   I suspect that if you make this change your problems will go away (certainly other problems will.)
sinisterAuthor Commented:
Thanks nietod;

I believe that your suggestion helped to reduce the memory leakage. Most of the memory problems were a result of not delete several structures properly. What is the correct way to free the memory. Here is what I had to create the structure:

SomeSTRUCT * myStruct = new SomeStruct

And to delete it I was using:

delete myStruct

Is this correct? I managed to use a workaround to fix the problem but I'm not sure of the above procedure.
That is correct.

If it is an array of something, you have to use "delete []"  instead of "delete"  Like

SomeStruct *MyStructArray = new SomeStruct[100];

delete [] MyStructArray;

What workaround did you use?
sinisterAuthor Commented:
Actually, I made a stupid mistake, I was de-referencing the pointer to another existing structure and then later deleting the pointer, but, ofcourse the original structure still existed.

Thanks for your help

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now