c - pthread_create passing arguments -


what wrong code? in function(), offset value printing -1. expect value 10. offset -1 giving sum = -1000. note:offset stored in heap memory.

test() prints expected output.

#include<stdio.h> #include<stdlib.h> #include<pthread.h>  pthread_t thread[2]; int sum = 0;  void* function(void *arg){    int i;    int offset = *((int *)arg);    printf("offset = %d \n",*(int *)arg);    for(i=0;i<1000;i++){       sum = sum+offset;    }    printf("\n sum = %d \n",sum);    pthread_exit(null); }  void test(void* val){    int offset = *((int *)val);    printf("inside test function.offset = %d \n",offset); }  int main(){    int ret;    int *offset = (int *)malloc(sizeof(int));     *offset = 10;    test(offset);     ret = pthread_create(&thread[0], null, &function,(void *)offset);    if(ret!=0)       printf("pthread create error \n");     pthread_join(thread[0],null);     return 0; } 

output:

inside test function.offset = 10 offset = -1 sum = -1000 

test platform: ubuntu 14.04 lts, gcc 4.8.4, linux kernel 3.13.0-57-generic.

gdb output:

breakpoint 1, function (arg=0x7fffffffdd4c) @ mutex_lock.c:11 11         int offset = *((int *)arg); (gdb) p *((int *)arg) $4 = -1 


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -