C程序接收信号SIGSEGV,矩阵乘法时的分割错误



是的,我已经通读了这样的问题,但没有一个证明对我的问题有用。我的程序有一个函数出现问题,该函数在另一个函数中一直完美运行。

程序接收信号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("nn");
}
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: %itcols: %in",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("Exittingn");
return 0;
}

该程序是一个矩阵 - 向量乘法,它读取一个未知大小的矩阵和一个匹配的向量(另外,如果你能提供更好的方法来读取具有更好代码的随机长度行,我会很高兴(。问题出在乘法代码上 - 尽管它应该可以工作,就像我编写的另一个大小固定的程序一样。所以它很好地读取矩阵和向量,然后给出段错误。

有什么想法吗?

你写sizeof(col),但col是一个整数,这意味着你的vec数组将始终分配sizeof(int)字节的内存(通常是4个字节,但取决于你的架构(。如果你想要一个双精度数组,你需要使用malloc(sizeof(double) * col)来分配适量的字节。

我怀疑您的res阵列也出现了同样的问题。在某些情况下,当您分配的空间后的空间仍可用于写入时,它可能会起作用,在这种情况下,计算机不会抱怨,因为错误定位的内存都在堆中。但是,如果您碰巧在错误块(太小(之后尝试写入受保护或保留的内存部分,操作系统将抛出 SegFault。

最新更新