views:

437

answers:

4

Let's say I pthread_create and then pthread_detach it. Now, from within the thread function, I malloc some block.

When the thread exits, will the malloc'ed memory be freed automatically?

(been googling for an answer to no avail...)

+1  A: 

I'm pretty sure it doesnt, you have to use free().

Pragma
+4  A: 

No - malloc'ed memory is only ever freed by an explicit 'free'.

Aaron
Or when the whole process exits - atleast on your typical desktop/server OS.
nos
+1  A: 

No. While any malloced memory is freed when the process exits, this same is not true for when the thread exits.

R Samuel Klatchko
+3  A: 
  • Threads share memory resources (at least POSIX).
  • malloc() / realloc() / free() memory management is not actually aware about threads (at least by now).
  • So you should treat results of malloc() as simple 'resource'. It is not thread-linked.

So now answer should be obvious, any memory allocated has no linkage to threads so it is not free()'d on thread exit. Of course you can provide some special handling mechanics but it is not done automatically.

Good side of this is you can pass memory allocation between threads in other words allocate such resource in one thread and then free from another (is it good for you or not).

Hope this would be useful explanation, think about allocated memory pointer as about any process-level descriptor.

Roman Nikitchenko