是的,我已经通读了这样的问题,但没有一个证明对我的问题有用。我的程序有一个问题,而这个功能在另一个程序中运行得很好。
Program received signal SIGSEGV, Segmentation fault. _int_malloc (av=0x7ffff7dd8e40, bytes=32) at malloc.c:4703 4703 malloc.c: No such file or directory.
这是我收到的错误。
这是我的程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void endl()
{
printf("\n\n");
}
void loadVector(FILE *infile, double *vector, int col)
{
int i;
for(i=0;i<col;i++)
{
fscanf(infile,"%lf",&vector[i]);
}
printf("vector read...\n");
}
void printVec(double *vect, int run)
{
int k;
for(k=0;k<run;k++)
{
printf("%.2f ",vect[k]);
}
}
double* duplic(double* matr, double *vect, double *sol, int col, int row)
{
int k, l;
for(k=0;k<row;k++)
{
for(l=0;l<col;l++)
{
sol[k] += matr[col*k+l] * vect[l];
}
}
return sol;
}
int main(int argc, char **argv)
{
endl();
printf("=== ===");
endl();
if(argc!=3)
{
perror("not enough arguments");
endl();
return 1;
}
char ins[300];
char *cut;
int row=0, col=0, rnr = 1, index = 0;
double temp;
double *mat = NULL;
double *vec = NULL;
double *res = NULL;
FILE *in;
in = fopen(argv[1], "r");
while(fgets(ins,sizeof(ins),in) != NULL)
{
col = 0;
cut = strtok(ins," ");
while(cut != NULL)
{
col++;
sscanf(cut,"%lf",&temp);
if(mat==NULL)
{
mat = malloc(sizeof(temp));
*mat = temp;
}
else
{
rnr ++;
mat = realloc(mat,sizeof(mat)*rnr);
index = rnr - 1;
*(mat+index)=temp;
}
cut = strtok(NULL," ");
}
row ++;
}
fclose(in);
printf("Matrix read...");
endl();
printf("Printing matrix: ");
endl();
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%.2f ",mat[col*i+j]);
}
printf("\n");
}
endl();
// printf("rows: %i\tcols: %i\n",row,col);
vec = malloc(sizeof(col));
FILE *inv;
inv = fopen(argv[2],"r");
loadVector(inv,vec,col);
endl();
printVec(vec,col);
endl();
res = malloc(sizeof(row));
res = duplic(mat,vec,res,col,row);
printf("Solution-vector calculated...");
endl();
printf("\nSolution vector:");
endl();
printVec(res,row);
endl();
free(mat);
free(vec);
free(res);
fclose(inv);
printf("Exitting\n");
return 0;
}
该程序是一个矩阵 - vector 乘法程序,它读取一个未知大小的矩阵和一个匹配 vector (此外,如果您可以提供更好的方法来读取具有更好代码的随机长度行,我'祝你开心)。 问题出在乘法代码上——尽管它应该可以工作,因为我写的另一个程序是固定大小的。 所以它很好地读取矩阵和 vector ,然后给出段错误。
有什么想法吗?
最佳答案
你写sizeof(col)
,但是col
是一个整数,这意味着你的vec
数组总是分配sizeof (int)
字节的内存(通常为 4 字节,但取决于您的体系结构)。如果您想要一个包含 col 个 double 的 double 组,您需要使用 malloc(sizeof(double) * col)
来分配正确数量的字节。
我怀疑您的 res
数组也出现了同样的问题。在您分配的空间之后的空间仍然可用于写入的某些情况下,它可能会起作用,在这种情况下计算机不会提示,因为 malloc 的内存都在堆中。但是,如果碰巧您尝试在 malloc block (太小)之后写入 protected 或保留的内存部分,操作系统将抛出 SegFault。
关于C 程序接收到信号 SIGSEGV,矩阵乘法时出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44119259/