I have a question about variable scope and memory management in C. I am writing a program that listens for a socket connection and then launches a new thread to handle that client. The main while() loop can launch many separate threads. My question is this:
If I don’t use dynamic memory allocation (no malloc()), and instead have a variable locally declared as shown below, is it safe to use that variable in the called thread, even after the next iteration of the loop takes place?
while(1)
{
// Accept new socket connection here
// ...
pthread_t pt;
struct mypthreadargs args;
rc = pthread_create(&pt, NULL, handle_client, &args);
// The handle_client() function makes extensive use of the 'args' variable
}
What happens to the args variable (and the pt variable) after the thread has been created? Is the memory lost once the while() loop starts over, or is it safe to use them as I have?
Thanks!
No, you don’t want to do this.
It may or may not work, depending on exactly how this all gets invoked — realistically, on most architectures, with most compilers, the memory pointed to by &args will continue to be valid, but you will most likely end up with multiple threads using the same myptreadargs struct, which you probably don’t want (the actual behavior is undefined, this is only a likely outcome).
Instead,
malloc( )thestruct mypthreadargs.If you really want a way around this, and you’re willing to live with a maximum number of threads in flight at once, you could set up an array of args structs and use a new one for each iteration, and mark them as available when the called threads are done with them. At that point, you’re basically reimplementing a limited
malloc( ), however, so I would question the wisdom of the exercise.