开发者

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 开发者_JAVA百科within the thread context, I allocated some memory using malloc().

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


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


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


Thats pretty much the difference between threads and processes, processes own their resources like heap memory threads don't. If you want that functionality then you want a process not a thread.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜