Search code examples
c++multithreadingpthreadsdynamic-memory-allocation

Pthreads and dynamic memory


My thread routine looks like this

void * dowork(void * args)
{
    char* ptr = new char[25];
    memset(ptr, 0, sizeof(ptr));
    // Do some operations with ptr
    // What if I call delete[] ptr
}

I've initialized 5 threads. Now the questions,

  1. Is this thread safe?
  2. Which thread owns the memory?
  3. Will ptr re-initialize every time a new thread processes the dowork? If yes, what will happen to the memory allocated earlier?
  4. What if delete[] ptr is used at end of dowork?

Solution

    1. The ptr is local pointer so no other thread will interfere with it as long as you not communicate the pointer to another thread.

    2. Two threads running this function will allocate 1 char[25] array each. But the thread is not the owner its rather the process that owns it.

    3. ptr will re initialize and the old memory will not be deleted on thread join. So if no delete is used it will leak memory.

    4. delete[] would be good to use yes.

    To explain the ptris allocated by the operative system and every call of new will allocate a new pointer from the operative system. The value of ptr ie where it points, is a local stack variable hence local to the thread and no other threads can get its value as long as it not is communicated.