Reputation: 10962
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
?Upvotes: 0
Views: 1634
Reputation: 359
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.
Upvotes: 4
Reputation: 333
Alright, here are some of the tips you might find useful.
1) Thread safety is a computer programming concept applicable in the context of multi-threaded programs. A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time. (c) Wiki
In other words, this thread is safe if it doesn't cause the deadlocks or mess up with the shared data. In the piece of code You've provided there is no shared data used.
2) "Which thread owns the memory" the questions is a bit ambiguous to me - are you talking about virtual memory provided for thread execution or the "new char[]" construction?
3) When you call pthread_create() (assuming by syntax) you send the pointer to function , however the concept of local variables still applies. In other words any local variables are redefined in the process of new thread's creation. To the next part: every time you call pthread_create() it creates an instance which would run the thread pseudo-independently, consider it like calling the same function a lot of times. It's not a problem if 1st instance is already halfway done when the second just starts, their local variables are not related to each other. You have to worry about shared data.
4) You have to use delete[] ptr in the end of your function. If it is called over 1000 times it might cause serious bugs like "can't allocate memory"
Hope this is helpful. Cheers, Constantine
Upvotes: 1