snakeGame * createSnakeGame()
{
int row = 10;
int col = 10;
snakeGame * game = (snakeGame *) malloc(sizeof(snakeGame));
game->rows = row;
game->columns = col;
for (int i = 0; i < row; i++)
{
if (i == 0 || i == row - 1)
{
for (int j = 0; j < col; j++)
{
game->board[i][j] = BORDER;
}
}
else
{
game->board[i][0] = BORDER;
game->board[i][col - 1] = BORDER;
}
}
return game;
}
typedef struct
{
snakeEntity ** board;
int rows;
int columns;
} snakeGame;
typedef enum
{
SNAKE_HORIZONTAL,
SNAKE_VERTICAL,
SNAKE_UP_RIGHT,
SNAKE_UP_LEFT,
SNAKE_DOWN_RIGHT,
SNAKE_DOWN_LEFT,
FOOD,
BORDER,
EMPTY
} snakeEntity;
int main()
{
snakeGame * game = createSnakeGame();
printf("Success");
return 0;
}
The print statement is not reached because the program hangs and abruptly exits after a random amount of time.
I have tried allocating the struct in different ways, such as accounting for the array size and initialising the board separately. However, the same UB remains.
// Adding the array size to the allocated memory
snakeGame * game = (snakeGame *) malloc(sizeof(snakeGame) + (row * col * sizeof(snakeEntity)));
// Allocating memory to each row individually to the size of the column
game->board = (snakeEntity **) malloc(row * sizeof(snakeEntity));
for (int i = 0; i < row; i++)
{
game->board[i] = (snakeEntity *) malloc(col * sizeof(snakeEntity));
}
// Initialising the board separately
snakeGame * game = (snakeGame *) malloc(sizeof(snakeGame));
snakeEntity ** board = (snakeEntity **) malloc(row * col * sizeof(snakeEntity));
game->board = board;
I would appreciate some advice on how to solve the problem.