Jason Holley
Jason Holley

Reputation: 43

Struct loses track of variables when using pthread_create

I am trying to create a new thread that runs a function called csvSearch. The function requires 3 pieces of information, so I put those into a struct.

csvSearch takes a (void *) as its argument, and when casting that pointer back to a pointer to the struct, somehow I lose the data stored in outpath and column, two of the struct's fields.

This is the struct definition:

typedef struct {
    char path[256];
    char outpath[256];
    char column[32];
} Data;

When creating the thread I used the following code

Data *data = malloc(sizeof(Data *));

strcpy(data->path, path);
strcpy(data->outpath, outpath);
strcpy(data->column, column);

pthread_create(&threads[threadCount], NULL, csvSearch, data);

This is a summary of csvSearch, the function I'm trying to call

void *csvSearch(void * data){

    Data * input = (Data *) data;

    char * path = input->path;
    char * outpath = input->outpath;
    char * column = input->column;

//path is the correct string, but outpath and column are both empty strings
}

I've used gdb to test this extensively, and have been unable to find the issue. I know that up until pthread_create, data contains the proper information, and that I get the same memory address and size when it's cast back into a Data *, but input->outpath and input->column are both filled with null characters.

Is something in my syntax incorrect? Or can you not pass information to a function in a new thread this way?

Upvotes: 1

Views: 41

Answers (1)

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

Data *data = malloc(sizeof(Data *));

is allocating memory for a Data* and not Data.You need

Data *data = malloc(sizeof(Data));

Upvotes: 3

Related Questions