Austin Moore
Austin Moore

Reputation: 1412

Why is this variable being set to false?

I have a function that is supposed to check the possible answers to a certain coordinate on a sudoku board. I just need you to focus on the variable first however. For some reason first is set to false and I have no idea why.

Function:

void displayPossible(int board[][9], char input[], int &row, int &col)
{
  bool first = true;                          // variable instantiated and set to true
  cout << "First " << first << endl;

  bool possible[9];                           // I dont touch `first` at all
  computeValues(board, possible, row, col);   // between these two lines..

  cout << "First " << first << endl;          // by this point it is false. WHY!?
  cout << endl;

  cout << "Possible: ";
  for(int i = 0; i < 9; i++)
    cout << possible[i];
  cout << endl;

  cout << "First " << first << endl;
  cout << "The possible values for '" << input << "' are: ";
  // if I say 'first = true' right here, i get my expected outcome
  for(int i = 0; i < 9; i++)
    {
      if(possible[i] && first == true)
        {
          first = false;
          cout << i;
        }
      else if(possible[i] && first == false)
        cout << ", " << i;

      else
        ;
    }
  cout << endl;
}

Output:

First 1
First 0

Possible: 000010001
First 0
The possible values for 'd1' are: , 4, 8

Compute Values:

void computeValues(int board[][9], bool possible[], int row, int col)
{
  for(int i = 0; i < 9; i++)
    possible[i] = true;

  for(int iRow = 0; iRow < 9; iRow++)
    possible[board[iRow][col]] = false;

  for(int iCol = 0; iCol < 9; iCol++)
    possible[board[row][iCol]] = false;

  for(int iRow = 0; iRow < 2; iRow++)
    for(int iCol = 0; iCol < 2; iCol++)
      possible[board[row/3*3 + iRow][col/3*3 + iCol]] = false;

  if(board[row][col] != 0)
    possible[board[row][col]] = true;
}

Upvotes: 1

Views: 244

Answers (4)

Mike Seymour
Mike Seymour

Reputation: 254461

computeValues must be writing beyond the end of one of the arrays you pass to it (most likely possible). This is corrupting the stack, overwriting the value of first, and possibly causing other less obvious mayhem.

Upvotes: 1

unwind
unwind

Reputation: 399823

Probably due to a bug in possibleValues() that overwrites the value of first in memory.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612964

Most likely is that computeValues has a buffer overrun which is corrupting the value of first. One obvious possibility is that it writes to possible with an out-of-bounds index. Since possible and computeValues are quite probably next to each other on the stack, that seems a likely explanation.

Upvotes: 4

Almo
Almo

Reputation: 15861

Looks to me like ComputeValues is accessing a pointer that points (erroneously) to &first.

Upvotes: 0

Related Questions