views:

312

answers:

1

If I detach an NSThread will Cocoa run it in a separate memory heap or memory zone? For example, if I were to detach a thread, use malloc to create a large buffer, and then let the thread exit, would I get that memory back in some kind of automatic thread cleanup, or would it be leaked?

What about if I used a POSIX thread (pthread) instead?

Note that I'm not interested in ObjC allocs or autorelease pools, I'm talking about low-level buffers e.g. int * foo = malloc(100000);

+6  A: 

An NSThread -- like a pthread -- will have a separate stack, but will share the same heap as the rest of the threads in your task. The threads & heaps of individual tasks are isolated.

The pattern you describe -- alloc in a thread, let thread exit -- will leak; the memory will not be recovered.

Doesn't matter what kind of thread you use.

For a very limited in size allocation, you could use a stack buffer which will be reaped when the thread exits. However, the stack size of threads are limited and it is quite easy to blow out the stack and cause your whole application to crash if you rely upon large stack allocations.

Use malloc() and free() when done.

bbum