Reputation: 10939
I have a question about returning results from a pthread executed function.
Related code:
void* thread_func(void* args)
{
float result = 0;
// ...do something
return (void*)&result;
}
// ... using code
float answer;
pthread_join(pthread_handle, &answer);
To me, this kind of solution doesn't seem like it should work safely because result
would reside on the stack of thread_func
and cease to exist after thread_func
returns. However, in all the tests I've done it seems to work flawlessly. Is there something I'm misunderstanding about why this is safe? If not and my tests just happened to work due to some fluke, how do I safely get the return value back from thread_func
safely?
Upvotes: 3
Views: 1055
Reputation: 182639
This isn't safe. You simply got lucky (or rather unlucky). After the function ends all automatic variables are lost (thus pointers to them are useless).
malloc
and return that memoryIn conclusion use some memory that will survive after the function ends.
Upvotes: 10