簡體   English   中英

C程序收到信號SIGSEGV,矩陣乘法時出現分段錯誤?

[英]C program received signal SIGSEGV, Segmentation fault at matrix-multiplication?

是的,我已經閱讀了類似的問題,但沒有一個對我的問題有用。 我的程序的一個功能出現問題,該功能在另一個程序中運行正常。

程序收到信號SIGSEGV,分段故障。 _int_malloc(av = 0x7ffff7dd8e40,字節= 32),位於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;
}

該程序是矩陣-向量乘法之一,它讀取大小未知的矩陣和匹配的向量( 同樣,如果您可以提供更好的方式來讀取具有更好代碼的隨機長度行,我會很高興的 )。 問題出在乘法代碼上-盡管它應該可以工作,就像我寫的另一個程序中確定大小的程序一樣。 因此它很好地讀取了矩陣和向量,然后給出了segfault。

有什么想法嗎?

您編寫了sizeof(col) ,但是col是一個整數,這意味着將始終為vec數組分配sizeof(int)字節的內存(通常為4字節,但取決於您的體系結構)。 如果要使用col數為double的double數組,則要使用malloc(sizeof(double) * col)分配正確的字節數。

我懷疑您的res陣列也發生了同樣的問題。 在某些情況下,分配的空間之后的空間仍可用於寫操作(在這種情況下,計算機不會抱怨)是可行的,因為malloc的內存全部在堆中。 但是,如果碰巧您嘗試在malloc分配的塊(太小)之后寫入受保護或保留的內存部分,則操作系統將拋出SegFault。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM