二维数组赋值和线程调用中的分段错误

时间:2013-12-14 19:39:11

标签: c linux segmentation-fault pthreads

我写了下面的代码来实现矩阵乘法,但是我反复得到了分段错误。一切似乎都好。任何人都可以告诉我这是什么问题。

这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int matrixSize;
double ** a, ** b, ** c;

typedef struct tparms {
    int row;
    int col;
}tparms_t;

double ** allocateMatrix() {
  int i;
  double *vals, **temp;

   //allocate values
    vals = (double *) malloc (matrixSize * matrixSize * sizeof(double));

       // allocate vector of pointers
    temp = (double **) malloc (matrixSize * sizeof(double*));

    for(i=0; i < matrixSize; i++)
        temp[i] = &(vals[i * matrixSize]);
        return temp;
 }

void* multiply (void* _arg){
    tparms_t * arg = (tparms_t *) _arg; 
    int i;
    double sum;
    for (i=0; i<matrixSize; i++)
        sum += a[arg->row][i] * b[i][arg->col];
    c[arg->row][arg->col] = sum;
}

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

    pthread_t *threads;

    if (argc != 2) {
        printf("Usage: %s <size>,  where size is dimension of square matrix\n", argv[0]);
        exit(1);
    }
    int matrixSize = atoi(argv[1]);

    threads = (pthread_t *) malloc(matrixSize * matrixSize * sizeof(pthread_t));

    a = allocateMatrix();
    b = allocateMatrix();
    c = allocateMatrix();

    int i, j;


    for (i=0; i<matrixSize; i++){
        for (j=0; j<matrixSize; j++){

            a[i][j] = i + j; 
            b[i][j] = i + j; 
        }
    }

    for (i=0; i<matrixSize; i++){
        for (j=0; j<matrixSize; j++){

            tparms_t * tt = (tparms_t *)malloc(sizeof(tparms_t));
            tt->row = i;
            tt->col = j;

            pthread_create(&threads[i*matrixSize + j], NULL, multiply, (void*)tt);

        }
    }

    // two for for arrays
    for (i=0; i<matrixSize; i++){
        for (j=0; j<matrixSize; j++){
            //do something ...
            pthread_join(threads[i*matrixSize+j], NULL);
        }
    }
    // end of two fors
}

有一个结构将数据传递给线程,分配函数来分配数组,在main函数中我决定为每个矩阵元素创建一个线程。然后是一个连接函数,等待所有线程完成它们的工作并创建c矩阵元素。

1 个答案:

答案 0 :(得分:2)

你有int matrixSize = atoi (argv[1] );。删除int,因为这会创建另一个matrixSize的本地实例。