gpt4 book ai didi

c - 在 C 中将字符串文字作为参数传递时的段错误

转载 作者:行者123 更新时间:2023-11-30 18:23:38 24 4
gpt4 key购买 nike

我试图编写一个程序来使用 C 中的 OpenMP 执行矩阵乘法。每当我尝试将字符串文字作为参数传递给函数时,我都会遇到段错误错误。

#include<stdio.h>
#include<time.h>
#include<omp.h>

struct matrix{
int r;
int c;
int mat[1000][1000];
};

void read_matrix(char* fname, struct matrix* m){
FILE *fp;
fp = fopen(fname,"r");

fscanf(fp, "%d %d",&m->r,&m->c);
for(int i=0;i<m->r;i++){
for(int j=0;j<m->c;j++){
fscanf(fp, "%d", &m->mat[i][j]);
}
}
fclose(fp);
}

void write_matrix(char* fname, struct matrix m){
FILE *fp;
fp = fopen(fname,"w");
fprintf(fp,"%d %d\n",m.r,m.c);
for(int i=0;i<m.r;i++){
for(int j=0;j<m.c;j++){
fprintf(fp,"%d\n",m.mat[i][j]);
}
}
fclose(fp);
}

void main(){
struct matrix m1;
struct matrix m2;
struct matrix res;
read_matrix("m1",&m1);
read_matrix("m2",&m2);
int r1 = m1.r;
int c1 = m1.c;
int c2 = m2.c;
res.r = r1;
res.c = c2;
for(int i=0;i<r1;i++){
for(int j=0;j<c2;j++){
res.mat[i][j] = 0;
}
}
#pragma omp parallel
{
#pragma omp for
for(int i = 0; i < r1; i++){
for(int j = 0; j < c2; j++){
for(int k = 0; k < c1; k++){
#pragma omp atomic update
res.mat[i][j] += m1.mat[i][k]*m2.mat[k][j];
}
}
}
}
write_matrix("res",res);

}

代码显示Segmentation fault (core dumped)运行时。当在GDB上运行时,它表明 Program received signal SIGSEGV, Segmentation fault.
0x0000000000400ad9 in main () at mm.c:40
40 read_matrix("m1",&m1);
在第一次 read_matrix() 调用之前,我添加了一条 printf 语句 printf("check\n");
printf 调用现在开始抛出段错误。我假设传递字符串文字是错误的原因。代码可能有什么问题?

最佳答案

Before the first read_matrix() call I added a printf statement printf("check\n"); The printf call now started throwing a segmentation fault.

我认为这可能会发生,因为您在堆栈上分配了结构矩阵。每个矩阵大约为 4MB,因此堆栈上有 12MB。我猜它会创建站点(堆栈溢出)。

尝试对矩阵使用静态变量或动态分配它们。它可能会解决你的问题。如果没有,永远不要在堆栈上分配 12MB 的结构...

关于c - 在 C 中将字符串文字作为参数传递时的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52350939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com