views:

517

answers:

2

Suppose I have the following code:

while(TRUE) {
  pthread_t *thread = (pthread_t *) malloc(sizeof(pthread_t));
  pthread_create(thread, NULL, someFunction, someArgument);
  pthread_detach(*thread);
  sleep(10);
}

Will the detached thread free the memory allocated by malloc, or is that something I now have to do?

+7  A: 

No. pthread_create() has no way of knowing that the thread pointer passed to it was dynamically allocated. pthreads doesn't use this value internally; it simply returns the new thread id to the caller. You don't need to dynamically allocate that value; you can pass the address of a local variable instead:

pthread_t thread;
pthread_create(&thread, NULL, someFunction, someArgument);
Commodore Jaeger
+1  A: 

You need to free the memory yourself. It would be preferable to simply allocate the pthread_t variable on the stack as opposed to the heap.

Andrew