D. Lucit
D. Lucit

Reputation: 71

C++ simple new & delete thread and memory leaks

I used threads in my code and found some memory leaks, so I tested the following simple code.

#include <thread>

void foo(){}

int main()
{
    for(; ;)
    {
        std::thread *th = new std::thread(foo)
        th->join();
        delete th;
    }
}

I tested it using VC++ Release mode without any change of settings, and I could also find memory leaks. When I checked the process using Windows Task Manager, the memory of this program was increasing.

I think the delete in my code doesn't work. Is there any reason why there are memory leaks?


More Detail

After I checked comments and the answer, I ran the program for more minutes. I could find the test program doesn't use more memory after few minutes. However I cannot sure why thread use more memory after delete (other class don't), and my program still shut down with increasing of memory usage after few minutes. In my program, only 11 threads are used for each loop, so memory usage increases slowly, and suddenly shut down.

Upvotes: 4

Views: 2280

Answers (1)

Morglod
Morglod

Reputation: 217

I think OS can't manage thread's memory so fast. 1) Check same code with some intervals 2) Which stats column in Windows Task Manager you look? Check "Allocated memory".

Upvotes: 1

Related Questions