I have some dynamic allocations which I want to make sure are freed when the thread exits/terminates.
Please consider the following scenario:
static void thread_cleanup_handler(void* arg)
{
free(arg);
}
static void* threadFunction(void* arg)
{
pthread_cleanup_push(thread_cleanup_handler, arg);
//do some work with arg...
pthread_cleanup_pop(1);
return NULL;
}
something* data = (something*)malloc(sizeof(something));
pthread_create(&id, &attr, threadFunction, (void*)data); //thread is created detached
Question is, if the created thread is cancelled (using pthread_cancel) before it actually started running (it has only been scheduled and has not been executed yet), will the cleanup handler be invoked or is this a potential memory leak?
Please not that the thread is created with PTHREAD_CREATE_DETACHED.