1

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.

Kamalesh P
  • 23
  • 7
  • Might be useful(not a dupe): [In C++, can new in one thread allocate the memory deleted by another thread?](https://stackoverflow.com/questions/31225837/in-c-can-new-in-one-thread-allocate-the-memory-deleted-by-another-thread). Also, [Is memory allocated with new ever automatically freed?](https://stackoverflow.com/questions/765971/is-memory-allocated-with-new-ever-automatically-freed) – Jason Aug 27 '22 at 11:40
  • 1
    Note that it's often the case that a pointer to a memory buffer allocated in one thread is then made available (one way or another) for another thread (or other threads) to use, and the other thread(s) continue using the memory buffer even after the allocating thread has exited. In a hypothetical system where the runtime automatically freed all memory allocated by a thread when the thread exited, all of the other threads in a program that used this technique would find themselves dereferencing dangling pointers and invoking undefined behavior. – Jeremy Friesner Aug 27 '22 at 14:35

2 Answers2

2

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.

user17732522
  • 53,019
  • 2
  • 56
  • 105
0

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