natenho natenho - 1 year ago 82
Linux Question

How to pass a local struct as parameter to pthread_create?

The following function doesn't work.

sometimes receive garbage instead of the struct data. What is wrong? I know that is some basic scope related problem, but I can't explain.

typedef void (*state_callback_t)(int state);

struct pin_thread_params
char pin[3 + 1];
state_callback_t callback_onchange;

extern int pin_monitor_create(const char * pin,
state_callback_t callback_onchange)
int ret;
unsigned long int thread;
struct pin_thread_params params;

//Setup struct
strcpy(, "123");
params.callback_onchange = callback_onchange;

//Create thread with struc as parameter
ret = pthread_create(&thread, NULL, pin_thread_function, &params);
if (!ret)
ret = pthread_detach(thread);

return ret;

static void * pin_thread_function(void * context)
struct pin_thread_params params;
memcpy(&params, context, sizeof(params));

//Sometimes the correct string, most time garbage
printf("Started monitoring %s",;

When params is malloc'ed before pthread_create, everything works fine, like this:

struct pin_thread_params * params;

//Setup struct with malloc
params = malloc(sizeof(struct pin_thread_params));
strcpy(params->pin, "123");
params->callback_onchange = callback_onchange;

Answer Source

struct pin_thread_params params is statically allocated and the address of it is not safe to use once the scope of it is over (i.e. after pin_monitor_create has returned). It may happen that sometimes the thread execution starts before the pin_monitor_create has exited and you see the valid data in params. However, the dynamically allocated memory is from heap and will be usable until you free it, so you always get valid data in params within pin_thread_function .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download