Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does exiting from a pthread release malloced memory?

Let's say I have started new thread with pthread_create() and then detached it using pthread_detach(). Now, from within the thread context, I allocated some memory using malloc().

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

like image 225
jldupont Avatar asked Nov 06 '09 19:11

jldupont


2 Answers

  • 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.

like image 141
Roman Nikitchenko Avatar answered Sep 25 '22 19:09

Roman Nikitchenko


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

like image 31
Aaron Avatar answered Sep 25 '22 19:09

Aaron