2016-11-28 78 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