From f93ea56076bc4fdcb4835f06d2baa64d6ce5e4df Mon Sep 17 00:00:00 2001 From: Aaro Saila Date: Wed, 21 Jan 2026 16:43:53 +0200 Subject: [PATCH] added null checks after allocations --- src/Board.c | 4 ++++ src/Snake.c | 4 ++++ src/utils.c | 1 + 3 files changed, 9 insertions(+) diff --git a/src/Board.c b/src/Board.c index 7a88e8f..e694002 100644 --- a/src/Board.c +++ b/src/Board.c @@ -5,6 +5,7 @@ #include "config.h" #include "Board.h" #include "Snake.h" +#include "utils.h" #define MAT_INDEX(mat, w, i, j) (mat)[(j) + (w) * (i)] @@ -16,6 +17,9 @@ Board board_alloc(const int width, const int height) { board.width_with_borders = board.width + 2; board.height_with_borders = board.height + 2; board.squares = (char*) malloc(sizeof(char) * board.width_with_borders * board.height_with_borders); + if (board.squares == NULL) { + mallocError("board.squares", __FILE__, "board_alloc"); + } for (size_t i = 1; i < board.height_with_borders; i++) { for (size_t j = 1; j < board.width_with_borders; j++) { diff --git a/src/Snake.c b/src/Snake.c index 2f4d442..19ce57f 100644 --- a/src/Snake.c +++ b/src/Snake.c @@ -3,6 +3,7 @@ #include #include "Snake.h" +#include "utils.h" extern const char snake_vis; @@ -31,6 +32,9 @@ Snake snake_alloc( snake.length = 1; snake.dir = init_dir; snake.parts = (BoardPiece*) malloc(sizeof(BoardPiece) * snake.max_length); + if (snake.parts == NULL) { + mallocError("snake.parts", __FILE__, "snake_alloc"); + } snake.parts[0] = (BoardPiece) { .x = init_x, .y = init_y, .vis_char = '&' }; return snake; diff --git a/src/utils.c b/src/utils.c index 1edcab1..24ab7fe 100644 --- a/src/utils.c +++ b/src/utils.c @@ -18,6 +18,7 @@ int randomInt(const int start, const int end, const unsigned int seed) { return result; } +// TODO: Make a general error logging function and macro void mallocError(const char* varName, const char* fileName, const char* functionName) { printf("Ran out of memory to allocate to %s in %s/%s\n", varName, fileName, functionName); exit(1);