Prechádzať zdrojové kódy

added null checks after allocations

Aaro Saila 8 mesiacov pred
rodič
commit
f93ea56076
3 zmenil súbory, kde vykonal 9 pridanie a 0 odobranie
  1. 4 0
      src/Board.c
  2. 4 0
      src/Snake.c
  3. 1 0
      src/utils.c

+ 4 - 0
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++) {

+ 4 - 0
src/Snake.c

@@ -3,6 +3,7 @@
 #include <assert.h>
 
 #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;

+ 1 - 0
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);