pthreads - Can't pass in struct into function for pthread_create correctly -


i'm trying pass in professor struct professor function can't information stored in pass function. suspect has how malloc'd p thought freeing after it's completed solve problem. segfault when try print *professor->id, because apparently decides read p memory location 0x0, though it's not in main

typedef struct{     int *id;     int *assignings;     int *min_wait;     int *max_wait;     int *min_assignments;     int *max_assignments;     int *min_hrs;     int *max_hrs; } professor;  professor* makeprofessor(){     professor *professor = malloc(sizeof *professor);     return professor; }  void * professorfunc(void *p){     professor *professor = (professor*)p;     fprintf(stdout,"starting professor %d\n", *professor->id);     pthread_exit(0); }  int main(int argc, char **argv){ //creating threads     pthread_t professor[num_professors];     professor *p;     int i;     int id;     for(i = 0; < num_professors; ++i){             id = + 1;             p = malloc (sizeof *p);             p->id = &id;             if(pthread_create(&professor[i], null, professorfunc, (void*)p) != 0){                     perror("pthread_create");                     exit(1);             }             free(p);     }     for(i = 0; < num_professors; ++i){             if(pthread_join(professor[i], null) != 0){                     perror("pthread_join");                     exit(1);             }     } 

you allocating array of professor structs, , freeing them, before thread has chance operate on them. better way implement this, allocate whole array, process them, , free memory, once know threads have exited (example below).

pthread_t professor[num_professors]; professor *p; int i; int id; p = malloc (sizeof(*p) * num_professors); for(i = 0; < num_professors; ++i){         id = + 1;         p->id = &id;         if(pthread_create(&professor[i], null, professorfunc, (void*)p) != 0){                 perror("pthread_create");                 exit(1);         } } for(i = 0; < num_professors; ++i){         if(pthread_join(professor[i], null) != 0){                 perror("pthread_join");                 exit(1);         } } free(p); 

Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -