【问题标题】:c error in array segmentation faultc数组分段错误中的错误
【发布时间】:2017-04-11 21:45:38
【问题描述】:

我尝试在 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 中的段错误(核心转储), 为什么??

【问题讨论】:

  • if (argc != 3) 嗯?对于 a.out ??
  • 检查参数个数是否超过3。

标签: c linux macos pthreads posix


【解决方案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;
};

这样你就完成了。

【讨论】:

    【解决方案2】:

    在您的代码中,您正在调用

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

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

    您需要提供一个函数指针,例如 calculateMult 或类似的东西。

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      相关资源
      最近更新 更多