【问题标题】:Hello people, I get an segmentation fault on the program below and I can't figure it out大家好,我在下面的程序中遇到了分段错误,我无法弄清楚
【发布时间】:2015-08-08 20:13:24
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int p=2; //nr de thread-uri
int **a, **c;
int n=4;
void *Matrix_Add(void *);


int main(){

int i, j, q;
int *params;                                
pthread_t *ids;                             

a=(int**)malloc(sizeof(int*)*n);            
c=(int**)malloc(sizeof(int*)*n);
  for(i=0; i<n; i++){
      a[i]=(int*)malloc(sizeof(int)*n);
      c[i]=(int*)malloc(sizeof(int));
    }
params=(int*)malloc(sizeof(int)*p);             
ids=(pthread_t*)malloc(sizeof(pthread_t)*p);    

  for(i=0; i<n; i++){                       
    for(j=0; j<n; j++){
        a[i][j]=1;
        }
        }
  for(i=0; i<n; i++){
        for(j=0; j<n; j++)
            printf("%d ", a[i][j]);
            printf("\n");
        }

  for(q=0; q<p; q++){
    params[q]=q;
    pthread_create(&ids[q], 0, Matrix_Add, (void*)params[q]);
}
for(q=0; q<p; q++){
    pthread_join(ids[q], 0);
}




return 0;


}

void *Matrix_Add(void *params){

int i, j, first, last;
int q=*(int*)params;
int s=n/p;
first=q*s;
last=first+s;

for(i=first; i<last; i++){
    c[i]=0;
    for(j=0; j<n; j++){
        c[i]+=a[i][j];
    }
}
return 0;
}

程序应该创建 2 个线程,将 2d 数组的行 2 除以 2(每个线程 2 行),然后计算矩阵 a 的每一行的总和并将其写入矩阵 c。矩阵 c 应该有 n 行和 1 列。

【问题讨论】:

    标签: c multithreading segmentation-fault


    【解决方案1】:

    将 pthread_create 行上的 (void*)params[q] 更改为 (void*)&amp;params[q]。 Matrix_Add 期望它的 params 参数是一个 int*,而不是一个 int。

    【讨论】:

    • 5k rep之后,你应该知道不要回答这些类型的问题。
    • 嗯。它会关闭,我会帮助某人。我可以忍受。
    • 是的,我设法弄明白了,但现在我遇到了另一个问题。每行的总和似乎是 16,我不明白为什么。感谢您的帮助!
    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多