I get error when trying to allocate 2D array, then use them

0

I am trying to allocate a 2D array in a function, but when I use this function my whole SDL apps crashes. If I comment out just the line where I call the function, there is no problem.

The return I get: Process returned -1073741819 (0xC0000005)

My Structs:

typedef struct Game
{
    int x;
    int y;
    GameMode mode;
    Field field;
} Game;

typedef struct Cell
{
    CellType type;
    bool shown;
    bool marked;
} Cell;

This is how I initialize the Game and set a pointer of pointer for Cell.

Game game;
Cell **cells;
setup_ui(&game, cells);

setup_ui function: static int setup_ui(Game *game, Cell **cells)

In the setup_ui I have the function which causes the problem:

cells = setup_cells(game, cells);

And the function itself:

Cell** setup_cells(Game *game, Cell** cells){
    cells = (Cell**) malloc(game->y*sizeof(Cell*));

    for(int x=0; x<game->y; x++){
        cells[x] = (Cell*) malloc(x * sizeof(Cell));
    }

    for(int i=0; i<game->x; i++){
        for(int j=0; j<game->y; j++){
            cells[i][j].type = simple;
            cells[i][j].shown = false;
            cells[i][j].marked = false;
        }
    }
    return cells;
}
c
asked on Stack Overflow Nov 10, 2020 by gmark11

1 Answer

3

First of all, there's a mistake here:

for(int x=0; x<game->y; x++){
    cells[x] = (Cell*) malloc(x * sizeof(Cell));
}

This should be malloc(game->x * sizeof(Cell)), since x is the current index, but game->x is the actual width. However, the error comes from the fact that here:

for(int i=0; i<game->x; i++){
    for(int j=0; j<game->y; j++){
        cells[i][j].type = simple;
        cells[i][j].shown = false;
        cells[i][j].marked = false;
    }
}

i can go up to game->x, and j can go up to game->y, but the first dimension is of size game->y and the second dimension is of size game->x. So, you should flip the bounds of i and j.

answered on Stack Overflow Nov 10, 2020 by Aplet123

User contributions licensed under CC BY-SA 3.0