简体   繁体   中英

Unhandled exception

I try to implement the game described in the http://www.cprogramming.com/tutorial/game_programming/same_game_part1_p2.html . Although it worked well initially, from some point till now crashes at runtime while build does not indicate any error. The problem appears as an “Unhandled Exception”-“Access violation reading location” on the line

return m_arrColors[m_arrBoard[row][col]];

in the function

COLORREF CSameGameBoard::GetBoardSpace(int row, int col)
{
  //  Check the bounds of the array
 if(row < 0 || row >= m_nRows || col < 0 || col >= m_nColumns)
   return m_arrColors[0];
 return m_arrColors[m_arrBoard[row][col]];
}

Any possible reason?

Update:

The program crashes the first time it tries to access

m_arrColors[m_arrBoard[0][0]];

m_arrColors and m_arrBoard are defined by the constructor:

CSameGameBoard::CSameGameBoard(void)
     :m_arrBoard(NULL),
  m_nColumns(15), m_nRows(15),
  m_nHeight(35),  m_nWidth(35)
 {
  m_arrColors[0] = RGB(  0,  0,  0);
  m_arrColors[1] = RGB(255,  0,  0);
  m_arrColors[2] = RGB(255,255, 64);
  m_arrColors[3] = RGB(  0,  0,255);
}

Update2: I added the command SetupBoard(); in the constructor' s body and it worked. However it is not proposed by the tutorial http://www.cprogramming.com/tutorial/game_programming/same_game_part1_p2.html and initially worked fine in my program without it as well.

The obvious reason is that you're accessing invalid indexes of the arrays - either m_arrColors or m_arrBoard .

For example, if m_arrBoard has dimensions 3x3 , and you try to access m_arrBoard[3][3] , you'll get a crash (probably, it's actually undefined behavior). - remember that C++ arrays are 0-based .

Run through it with a debugger, and check to see if this is happening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM