views:

41

answers:

3

Hi All, I have a thread function which allocates memory using malloc(). I kill the thread using pthread_kill without freeing the dynamically allocated memory.Will it be freed automatically once i call pthread_kill or there will be a leak?

+1  A: 

there will be a leak. how would pthreads kill function possibly know the names of variables that have been assigned via malloc? There is no garbage collection in C, if you call malloc somewhere, you better make sure that you call free somewhere else.

[Edit] Maybe you should just set a global flag variable associated with your thread, and have your thread poll that variable occasionally to know if and when it should terminate itself.

vicatcu
+3  A: 

As vicatcu says, there will be a leak.

I wouldn't ever recommending using pthread_kill unless you absolutely have to. Instead, you should create a signaling mechanism to let the thread know when it should be finished, and then join on the thread. And the thread function should poll that value occasionally, and if it gets a terminate signal, it should clean up its own resources and exit.

The other option, of course, is to try not to allocate memory in threads. But I guess you don't always get that luxury. :-)

Platinum Azure
+2  A: 

Memory you are allocating in one thread doesn't "belong" to that thread. It is allocated from the same global heap all the other threads are using your program. So you have to free all the memory you have allocated otherwise you end up with a leak.

Frank Meerkötter