Exception thrown at 0x00007FFD9ABF024E (ucrtbased.dll) in myapp.exe: 0xC0000005: Access violation reading location

Viewed 10

I'm trying to create a char matrix using dynamic allocation (char**). It represents a board where the margins are '#' character and in the middle is the ASCII 32 (blank space). When I run the code this massage appear: "Exception thrown at 0x00007FFD9ABF024E (ucrtbased.dll) in myapp.exe: 0xC0000005: Access violation reading location " in some cpp file. Here's my code:

#include <iostream>

using namespace std;

char** allocateBoard(int n)
{
char** Board = 0;
Board = new char* [n+2];
int i;
for (i = 0; i < n + 2; i++)
{
    Board[i] = new char[n * 2 + 2];
}

return Board;
}

void initBoard(char**& Board, int n)
{
int i, j;
for (i = 0; i < n; i++)
{
    for (j = 0; j < n * 2; j++)
    {
        if (i == 0 || i == n - 1) Board[i][j] = '#';
        else if (j == 0 || j == n * 2 - 1) Board[i][j] = '#';
        else Board[i][j] = 32;

    }
}
}

void showBoard(char** Board, int n)
{ 
int i, j;
for (i = 0; i < n; i++)
{
    for (j = 0; j < n * 2; j++)
    {
        cout << Board[i][j];
    }
    cout << endl;
}
}

int main()
{
int n = 4;

char** Board = 0;
Board = allocateBoard(n);

initBoard(Board, n);
showBoard(Board, n);

cout << endl;

showBoard(Board, n);

for (int i = 0; i < n * 2 + 4; i++)
{
    delete[] Board[i];
}

delete[] Board;

return 0;
}

Does anyone know where is the problem? As a very beginner I can't see where is the mistake. I've allocated more space in the matrix than I'm actually using so I can't figure why this message appears. Is the deallocation the problem?

Thanks!

0 Answers
Related