【发布时间】:2017-10-22 11:43:49
【问题描述】:
是的,我已经阅读了这样的问题,但没有一个证明对我的问题有用。我的程序有一个问题,该功能在另一个程序中运行良好。
程序收到信号SIGSEGV,分段错误。 _int_malloc (av=0x7ffff7dd8e40, bytes=32) at malloc.c:4703 4703 malloc.c: 没有这样的文件或目录。
这是我收到的错误。
这是我的程序:
#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;
}
该程序是一个矩阵-向量乘法程序,它读取一个未知大小的矩阵和一个匹配向量(另外,如果您可以提供更好的方法来读取具有更好代码的随机长度行,我'会很高兴)。 问题出在乘法代码上——尽管它应该可以工作,就像我写的另一个程序一样,它的大小是固定的。 所以它很好地读取了矩阵和向量,然后给出了段错误。
有什么想法吗?
【问题讨论】:
-
你应该做一些调试 - Valgrind 在这里会是一个很好的帮助(假设它是你平台上的一个选项)。
-
有趣的是,当我使用 Valgrind 运行它时,它没有出现任何问题并按预期运行。正常跑的时候又死了。
标签: c matrix malloc segmentation-fault