首页 文章

阵列分段故障中的c错误

提问于
浏览
2

我试图在osx和linux ubuntu的终端中运行这段代码:

#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;
};

我在终端运行这些命令:

cc -pthread main.c

./a.out 1 1

但它给了我段错误:osx中的11和linux中的段错误(核心转储),为什么?

2 回答

  • 0

    我认为您需要更改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;
    };
    

    所以你完成了 .

  • 1

    在你的代码中,你正在打电话

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

    其中,第三个参数 iint 但预期参数的类型为 void *(*start_routine) (void *) . 这会调用undefined behavior .

    你需要提供一个函数指针,如 calculateMult 或类似的东西 .

相关问题