pointers - C - pthread segmentation fault 11 -


i'm creating thread , passing pointer it. when cast pointer should (int*) have segmentation fault.

int *ptr = (int *)ptrtotal2; 

here code :

void *firstcalc(void *ptrtotal2){   int vala = 1;   int valb = 2;   int *ptr = (int *)ptrtotal2;   *ptr = vala + valb;   printf("value of vala = %d\nvalue of valb = %d\n", vala, valb);   printf("value of subtotal *ptrtotal1 = %d\n", *ptr);   pthread_exit(null); }  int main(int argc, char **argv) {    pthread_t thread1;   int *ptrtotal2 = 0;   int iret1;    iret1 = pthread_create(&thread1, null, firstcalc, (void*) ptrtotal2);    if(iret1){     fprintf(stderr,"error - pthread_create() return code: %d\n",iret1);     exit(exit_failure);   }    pthread_join( thread1, null);    exit(exit_success);  } 

dereferencing ptr in function firstcalc, when original pointer set 0, cause undefined behavior, in case segmentation fault.

int *ptr = (int *)ptrtotal2; *ptr = vala + valb; ... int *ptrtotal2 = 0; 

instead allocate memory integer, , pass created thread, , free after thread ends:

int *ptrtotal2 = malloc( sizeof( int ) ); if( !ptrtotal2 ) {     abort(); }  //... call pthread_create, pthread_join  free( ptrtotal2 ); 

note, have use allocated memory (use malloc), because reading automatic variable different thread implementation defined.

6.2.4 storage durations of objects

  1. the result of attempting indirectly access object automatic storage duration thread other 1 object associated implementation-defined.

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -