2012-09-10 74 views
1
#include<pthread.h> 
#include<stdio.h> 
#include<sys/stat.h> 
#include<errno.h> 

#define SIZE 3 

/***I'm trying to send name of each file in a thread and trying to receive their respective size in main *******/ 

void *doit(void *name) 
{ 
     int *size; 
     struct stat st; 
     char temp_name[30]; 
     memset(temp_name, '\0', sizeof(temp_name)); 
     strcpy(temp_name, (char *)name); //type casted 
     stat(temp_name, &st); 
     *size = st.st_size; //calculated the size 

     printf("File name is: %s\n", temp_name); 
     printf("File size is: %d\n", *size); 
     pthread_exit((void *)size); //exited from thread 
} 

int main(int argc, char *argv[]) 
{ 
     pthread_t th_id[SIZE]; 
     int ret_val; 
     int i; 
     void **size[SIZE]; 
     for(i=0; i<SIZE;i++) 
     { 
       size[i] = (void **)malloc(30*sizeof(void *)); //allocated memory to void double pointer 
       if(size[i] == NULL) 
       { 
         printf("Memory not allocated to %dth member of size\n", (i+1)); 
       } 
     } 
     for(i=0; i<3; i++) 
     { 
      /*****Creating Thread**********/ 
       ret_val = pthread_create(&th_id[i], NULL, &doit, (void *)argv[1+i]); 
       if(ret_val != 0) 
       { 
         perror("Thread creation error\n"); 
         exit(0); 
       } 
       pthread_join(th_id[i], size[i]); 
       printf("Size is %d\n",**(int **)size[i]); //typecasted and printed 
     } 
     pthread_exit(NULL); 
     return 0; 
} 

在這個程序中,我在第一次調用pthread_join後出現了分段錯誤。當傳遞第一個文件時,我得到了正確的大小。但在撥打第二個文件時,我正在收到分段錯誤。對於gdb,我得到的結論是「** size [1]和** size [2]儘管使用了malloc,但是在main的開始處,我在分配內存時沒有收到錯誤信息。內存分配的初始。請幫我我應該怎麼辦。從C中的多個線程接收值

回答

1
int *size; 
    struct stat st; 
    char temp_name[30]; 
    memset(temp_name, '\0', sizeof(temp_name)); 
    strcpy(temp_name, (char *)name); //type casted 
    stat(temp_name, &st); 
    *size = st.st_size; //calculated the size 

你訪問一個uninitailized指針。你從來不size點什麼。

+0

你好@大衛,這件事是使用時對於單個文件,'doit'函數的代碼工作正常,我相信它現在應該可以正常工作,但是我認爲這個問題肯定是主要的,特別是在pthread_join和printf中,當我對它進行類型化時 – user1660455

+0

@ user1660455:是的不值得嘗試理解具有觸發UB的已知錯誤的代碼。修復bug和99%的時間,奧祕消失。 –