数组段错误中的 c 错误

标签 c linux macos pthreads posix

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

最佳答案

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

这样你就完成了。

关于数组段错误中的 c 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40839751/

相关文章:

java - Go JNI异常0xc0000005信号在外部代码执行期间到达

c - c 语言编程取决于操作系统

c - 基本的 Makefile 和头文件依赖

linux - 为什么 for 循环中的 file 命令表现得如此荒谬

linux - 在 "@"之前添加什么让它被系统忽略?

javascript - AngularJS 无法在 Chrome(Mac 和 Windows)中运行,但可以在 Safari 中运行

macos - 有没有适用于 Mac 的 Verilog IDE

结构标记可以在其作用域之前使用吗?

macos - 用于在文件中设置屏幕分辨率值的 Shell 脚本

linux - 将多个文件合并为一个文件,包括 shell 中不匹配的行