程序的总线错误/分段错误错误:这些错误意味着什么?

时间:2014-04-25 01:20:23

标签: c debugging recursion matrix segmentation-fault

我从此代码中收到总线错误10。当我输入打印语句时,我收到了分段错误错误。我在一个更大的程序中使用这两个函数来计算矩阵的行列式。这些错误意味着什么?我是C环境的新手。谢谢!

int* cofactor(int* matrix, int co_row, int co_column, int size_of_matrix){
 int* result;
 int i, offset;
 int row, column;

 result = duplicate_matrix(matrix, size_of_matrix-1);
 i = 0;
 offset = row*size_of_matrix+column;
 for (row = i; row < size_of_matrix; row++){
  for (column = i; column < size_of_matrix; column++){
   if ((row != co_row) && (column != co_column)){
    i = offset;
    i += 1;
    *result = i;
   }
   return result;
  }
 }
}

int* determinant(int* matrix, int size_of_matrix){
 int sign, x, one=1;
 int* size;
 int* result;
 int* the_sign;
 int* comatrix;

 sign = one;

 *the_sign = sign;
 *size = size_of_matrix;
 result = malloc(sizeof(int) * size_of_matrix*size_of_matrix);
 comatrix = malloc(sizeof(int) * size_of_matrix*size_of_matrix);
 if (*size == one){
  return size;
 }
 else{
  for (x = 0; x < size_of_matrix; x++){
    comatrix = cofactor(matrix, 0, x, size_of_matrix);
    *result = x;
    *result += *matrix;
    *matrix *= *the_sign;
    *the_sign *= *determinant(comatrix, size_of_matrix);
    *the_sign *= -1;
    *result = *the_sign;
  }
  return result;
 }
}

1 个答案:

答案 0 :(得分:1)

关于总线错误故障和分段故障之间的区别,有一个很好的SO帖子。

https://stackoverflow.com/a/212585/2724703

它们通常意味着您的程序设计不合理,并且由于某种原因您尝试访问不合法的内存。在你的程序中,有许多问题需要纠正才能工作。为:

这里你的程序试图访问/写入未初始化的     指针因此可能导致总线/分段故障。您的程序似乎使用指针而不是正常变量,而不是必需的。

  

//这些变量应该定义为正常而不是指针   int size; int the_sign;

我认为您还应该开始查看编译器警告。在这些情况下,编译器应该在示例程序中给出类似于gcc / g ++的警告。请注意它们并纠正程序中的这些警告信息。

int* i;
int j;

*i = j;
  

$ g ++ -Wall foo.cpp foo.cpp:在函数'int main()'中:foo.cpp:13:7:   警告:'i'可能在此功能中未初始化使用   [-Wyybe-uninitialized] * i = j;          ^ foo.cpp:13:7:警告:'j'可以在此函数中未初始化使用[-Wyybe-uninitialized]

此外,您需要释放程序由 malloc 分配的内存。否则就会出现内存泄漏。