为什么我的递归函数中的循环无限?

时间:2014-07-26 20:29:03

标签: c++ loops if-statement recursion segmentation-fault

我有以下函数递归检查数独谜题中的每个方块以使其合法,并且当它运行时我一直遇到分段错误,因此我在每个地方都进行了cout检查以查看其中断的位置。不知何故,它停留在循环中并继续一遍又一遍地调用addSquare函数,而不会结束。我怎么让它停下来?

bool DoTheWork::addSquare(int& depth)
{
  depth++;
  cout << depth << endl;
  if(board.checkZeroes()==false){ //if the game is won, return true
    cout << "ifstatement1" << endl;
    return true;
  }
  else {
    for(int i = 0; i < 10; i++) {
      cout << "loop1" << endl;
      for(int j = 0; j < 10; j++) {
        cout << "loop2" << endl;
        if(this->board.getSquare(i,j)==0) { //go through each
          cout << "ifstatement2" << endl;
          for(int k = 1; k < 10; k++) {
            cout << "loop3" << endl;
            //try each number in that square for legality
            board.setSquare(i,j,k);
            //set that square to the number you are currently on
            if(board.isLegal()==false) {
              cout << "ifstatement3" << endl;
              board.unsetSquare(i,j);
            }
            //if the board is not legal for that number, unset that square
            if(addSquare(depth)==true) {
              cout << "ifstatement4" << endl;
              return true;
            }
            //recursive function, if method is true then it will return true
            board.unsetSquare(i,j);
          }
        }
      }
    }
  }
  return false;
  } // bool DoTheWork::addSquare(int& depth)

在终端中运行时,会打印以下内容: 循环1 循环2 ifstatement2 循环3 ifstatement3 130964 LOOP1 ... 然后直到它说“分段错误(核心转储)”

每次深度增加时,“ifstatement3”之后的数字会增加1。

包括下面的checkZeroes功能:

bool Board::checkZeroes()
{
  bool zeroPresent = false;
//assume there are no zeroes, easier for coding
  for(int i=0; i<9; i++) {
    for(int j=0; j<9; j++) {
      if(theBoard[i][j] == 0){
//go through each value of theBoard, if any are 0 return true
        zeroPresent = true;
      }
    }
  }
  return zeroPresent;
} // int Board::checkZeroes()

1 个答案:

答案 0 :(得分:1)

您永远不会更改将导致无限递归的depth的值,并且当堆栈访问不应被访问的内存时会发生分段错误。

我会在像Linux中的GDB或DDD这样的调试器中运行它。