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,
ptr
re-initialize every time a new thread processes the dowork
? If yes, what will happen to the memory allocated earlier?delete[] ptr
is used at end of dowork
?The ptr is local pointer so no other thread will interfere with it as long as you not communicate the pointer to another thread.
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.
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.
delete[]
would be good to use yes.
To explain the ptr
is 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.