简体   繁体   中英

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?

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

是为Data*而不是Data分配内存。你需要

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM