c - Segmentation fault 11 thread program -
i'm having error "segmentation fault 11" following code : created thread give in parameters struct.
i think problem in declaration of function *marit
.
sorry bad english french.
struct parametres { double *t; int n; //taille }; void *marit(struct parametres parametres) { int *somme =0; float *moyenne = 0; int i; for(i = 0; < parametres.n; i++) *somme = *somme + parametres.t[i]; printf("somme : %d",somme); *moyenne = (*somme/(parametres.n+0.0)); pthread_exit(moyenne); }` int main(int argc, char* argv[]) { float temps; clock_t t1, t2; t1 = clock(); struct parametres params; printf("salut √† toi !\n"); printf("donnez la taille du tableau :" ); scanf("%d", ¶ms.n); params.t = malloc( params.n * sizeof(double) ); int = 0; int nombre_aleatoire = 0; for(i=0; i<params.n; i++){ nombre_aleatoire = (rand() % 1000) + 1; params.t[i]=nombre_aleatoire; } pthread_t arith,quadrat,cubi; if(pthread_create(&arith, null, marit, (void*)¶ms) != 0) { perror("pthread_create"); exit(1); } double *result=0; pthread_join(arith, (void**)&result); printf("le resultat du thread : %f",result); return 0; }
i don't know what's problem.
there couple of problems code.
first, signature of marit
. must take sinlge void*
parameter.
second, somme
, moyenne
declared pointers, don't allocate memory them. causing segfault.
third, return value must void pointer. means must have size of pointer , value points must persist past call (returning address of automatic variable inside marit
not ok).
fourth, main
expects double returned, change type of moyenne
.
fixing 3 issues done this:
void *marit(void *param) { struct parametres *parametres = (struct parametres*)param; int somme =0; double moyenne = 0, *ret; int i; for(i = 0; < parametres->n; i++) somme = somme + parametres->t[i]; printf("somme : %d",somme); moyenne = (somme/(parametres->n+0.0)); ret = malloc(sizeof ret); *ret = moyenne; pthread_exit(ret); }
note that, when main
function done processing retrun value should free
it. in case, program ends right afterwards, freeing memory not necessary.
you need change printf in main
:
printf("le resultat du thread : %f", *result);
Comments
Post a Comment