2014-07-26 86 views
0

我有以下函数递归检查数独拼图中的每个正方形以使其合法,并且在运行时我不断收到分段错误,因此我将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 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() 
+0

我们需要足够的代码来复制问题。看到实际的输出也会有所帮助。 –

+0

如果您遇到分段错误,“cout”可能不会被刷新。您可能看不到*整个*输出。 – zmbq

+0

@zmbq他在每个'cout'语句中都有一个'endl',并且'endl'刷新。 –

回答

1

你永远不会改变的depth值,这将导致无限递归和分段故障时会发生不应该访问的堆栈存储器。

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