Home > database >  Does the memory allocated by new, is automatically deallocated when the thread ends?
Does the memory allocated by new, is automatically deallocated when the thread ends?

Time:08-27

Memory allocated for new, is deallocated automatically when thread joins main thread or I must deallocated them using delete()
Here is the example code,

#include <iostream>
#include <thread>
using namespace std; 

class thread_obj {
public:
    void operator()(int x)
    {
        int* a = new int;
        *a = x;
        cout << *a << endl;
    }
};
int main() {
    thread th1(thread_obj(), 1);
    thread th2(thread_obj(), 1);
    thread th3(thread_obj(), 1);
    thread th4(thread_obj(), 1);

    // Wait for thread t1 to finish
    th1.join();

    // Wait for thread t2 to finish
    th2.join();

    // Wait for thread t3 to finish
    th3.join();

    while (true) {
        // th4 is still running
        /*
            whether the memory allocated for (int* a = new int;) is freed automatically when thread 1, 2, 3 joins main thread 
            Does this cause memory leak or I must delete them manually?
        */
    }

    th4.join();
    return 0;
}

Memory allocated for new int in th1, th2, th3, th4.

After joining (th1, th2, th3) in main thread, are they deallocated automatically and free to use for th4?

Thanks in advance.

CodePudding user response:

Memory obtained by new is shared among all threads. When a thread exits nothing happens with it. It is not freed. Either the exiting thread or another thread must call delete explicitly to destruct the object that was created with new and to free the memory it allocated for that object. Otherwise the object continues to live and will never be destroyed by the program.

CodePudding user response:

NO the memory is not freed you will have to manually deallocated the memory allocated by delete

  • Related