-1

I've used visual studio 2017 (community edition) for a few months and made several applications but never came close to this compilation error that I've gotten here. I've found some threads with a similar error as mine but none of them actually helped.

Today I started opened visual studio and decided to make a classic tic-tac-toe console game. I started coding it but I never actually debugged every now and then. When I finally compiled and tested the program I got this error:

Exception thrown at 0x00007FFC120B0FE1 (ucrtbased.dll) in 
CppTicTacToe.exe: 0xC0000005: Access violation reading location 
0x0000000000000000.

I guess it's something due with syntax violation but no idea what it actually means. From the side of the console, it kind of starts and then it stops, but it doesn't actually close. This is the code, which seems to work fine:

#include "stdafx.h"
#include <iostream>

using namespace std;
using byte = unsigned char;

const enum letter { x = 'x', o = 'o' };

static letter human(x);
static letter bot(o);

const unsigned short _x = 3;
const unsigned short _y = 3;

const byte* board[_x][_y] =
{
    { 0, 0, 0 },
    { 0, 0, 0 },
    { 0, 0, 0 }
};

const unsigned char& get_board_value(unsigned short &x, unsigned short &y) {
    return *board[x][y];
}

void put_board_char(const byte* (&_char), unsigned short &x, unsigned short &y) {
    board[x][y] = _char;
}

void put_board_chars(const byte* (&chars)[_x][_y], unsigned short &chars_cnt_x, unsigned short &chars_cnt_y) {
    unsigned short x1, y1 = 0;

    for (x1 = 0; x1 < chars_cnt_x; x1++) {
        for (y1 = 0; y1 < chars_cnt_y; y1++) {
            put_board_char(chars[x1][y1], x1, y1);
        }
    }
}

void draw_board() {
    unsigned short x1, y1 = 0;

    for (x1 = 0; x1 < _x; x1 += 1) {
        cout << "-----" << endl;
        for (y1 = 0; y1 < _y; y1 += 1) {
            if (y1 == 3 || y1 == 6) {
                cout << board[x1][y1] << endl;
                continue;
            }
            cout << board[y1][x1] << "|";
        }
    }
}

void ai(void){
    //todo
}

void logic(void) {
    //todo
}

int main(int argc, const char ** argv[]) {

    while (1) {
        draw_board();
    }

    return 0;
}
Artide
  • 1
  • 3

1 Answers1

1
const byte* board[_x][_y] =
{
    { 0, 0, 0 },
    { 0, 0, 0 },
    { 0, 0, 0 }
};

You initialize elements of board to 0, thus nullptr.

In draw_board():

cout << board[y1][x1] << "|";

board[y1][x1] is nullptr, and you try to read from it.

zhm
  • 3,513
  • 3
  • 34
  • 55
  • The second observation is a bit misleading. Reading a `nullptr` is fine; reading _from_ a `nullptr` is not. However, that's happening here is that `byte` was a `typedef` for `unsigned char`. `std::cout` therefore interprets `byte*` as a C-style null-terminated string, and will read from it. – MSalters Apr 14 '17 at 06:58
  • @MSalters Thanks for clarify. :-) – zhm Apr 14 '17 at 07:02