2016-11-28 75 views
2

我試圖在OSX和Linux的ubuntu運行在終端的代碼:C的誤差

#include <pthread.h> 
#include <stdio.h> 
#include <unistd.h> 
int fact=1; //this data is shared by thread(s) 
int n; 
int x; 
int *arrayName; 

int main(int argc, char *argv[]) 
{ 

    if (argc != 3){ //check number of arguments 
     printf("Must use: a.out <integer value>\n"); 
     return -1; 
    } 
    int x = atoi(argv[1]); 
    n = atoi(argv[2]); 
    if (n < 0){ //check second passed argument 
     printf("%d Must be >=0\n", atoi(argv[2])); 
     return -1; 
    } 
    arrayName = (int *) malloc(n * sizeof(int)); 
    pthread_t tid[n]; 

    for(int i=0;i<n;i++){ 
     pthread_create(&tid[i], NULL, (void *) i, NULL); 
    } 
    int i=0; 
    while(i<n){ 
     pthread_join(tid[i],NULL); 
     i++; 
    } 
    i=0; 
    while (i<n) { 
     printf("Thread is %d",arrayName[i]); 
     i++; 
    } 
} 
void *calculateMult(void *i) { 
    int j = (int) i; 
    arrayName[j] = x * j; 
    return NULL; 
}; 

我跑在終端這些命令:

立方厘米-pthread main.c中

./a.out 1

但是它給了我段錯誤:11在osx 和段錯誤(核心轉儲)在linux, 爲什麼?

+0

'if(argc!= 3)'ehhh?爲_a.out <整數值> _ ?? –

+0

[請參閱此討論,爲什麼不在'C'中投射'malloc()'和家族的返回值。](http://stackoverflow.com/q/605845/2173917)。 –

+0

檢查參數的個數是否大於3。 –

回答

0

在代碼中,你打電話

pthread_create(&tid[i], NULL, (void *) i, NULL); 

,其中,第三個參數iint但預期參數是void *(*start_routine) (void *)類型。這調用undefined behavior

您需要提供一個函數指針,如calculateMult或類似。

1

我認爲您需要更改pthread_create調用,因爲您在pthread_create中通過了錯誤的參數。還請檢查從pthread_create返回。

你需要像這樣

int s = pthread_create(&tid[i], NULL, (void *)calculateMult, (void *)&i); 
if (s != 0) 
     printf("pthread_create failed"); 

而且你需要更改的功能:

void *calculateMult(void *i) { 
    int *j = (int*) i; 
    arrayName[*j] = x * (*j); 
    return NULL; 
}; 

所以你做。

+0

感謝它的工作原理。 –

+0

@jassimabdrhman然後upvote並接受答案.....老兄 – Mohan