From b6d200edbe0b6ef6b10fbd87d863766ca567b013 Mon Sep 17 00:00:00 2001 From: Nuutti Varvikko Date: Tue, 7 Sep 2021 15:20:40 +0300 Subject: [PATCH] check memory allocation --- game.c | 18 ++++++++++++------ game.h | 2 +- snake.c | 13 +++++++++++-- snake.h | 4 ++-- 4 files changed, 26 insertions(+), 11 deletions(-) diff --git a/game.c b/game.c index 6cc4b33..4c1ee1b 100644 --- a/game.c +++ b/game.c @@ -23,7 +23,9 @@ int run(void) timeout(1000.0 / INPUT_RATE); generate_apple(ARENA_WIDTH, ARENA_HEIGHT); - init_snake(); + if (!init_snake()) { + return QUIT; + } while (true) { if (process() == QUIT) { @@ -56,7 +58,9 @@ int process(void) break; } - update(); + if (!update()) { + return QUIT; + } return RUNNING; } @@ -89,7 +93,7 @@ int input(void) return RUNNING; } -void update(void) +int update(void) { if (!check_win_size()) { @@ -112,7 +116,9 @@ void update(void) if (!(state == PAUSE || state == GAME_OVER || state == INTERRUPT)) { if (grow_snake_next) { grow_snake_next = 0; - grow_snake(); + if (!grow_snake()) { + return 0; + } } else { update_snake(); } @@ -137,17 +143,17 @@ void update(void) draw(); refresh(); } + + return 1; } void draw(void) { draw_arena(ARENA_WIDTH, ARENA_HEIGHT); - /* print score */ sprintf(text_buffer, "\n\n Score: %d", score); draw_text(text_buffer); - // sprintf(text_buffer, "\nr - restart\nq - quit"); draw_text("\n\n r - restart\n q - quit"); if (state == GAME_OVER) { diff --git a/game.h b/game.h index 8df00f2..71546f3 100644 --- a/game.h +++ b/game.h @@ -28,7 +28,7 @@ enum { int run(void); int process(void); int input(void); -void update(void); +int update(void); void draw(void); #endif diff --git a/snake.c b/snake.c index ee94208..5a15e63 100644 --- a/snake.c +++ b/snake.c @@ -5,7 +5,7 @@ queue snake; int snake_dir; -void init_snake(void) +int init_snake(void) { struct node *nodes[SNAKE_MIN_LENGTH]; int i, x, y; @@ -15,6 +15,9 @@ void init_snake(void) for (i = 0; i < SNAKE_MIN_LENGTH; i++) { nodes[i] = (struct node *) malloc(sizeof(struct node)); + if (!nodes[i]) { + return 0; + } nodes[i]->x = x + i; nodes[i]->y = y; @@ -23,6 +26,7 @@ void init_snake(void) } snake_dir = RIGHT; + return 1; } void empty_snake(void) @@ -90,10 +94,15 @@ void insert_snake_node(struct node *new) } } -void grow_snake(void) +int grow_snake(void) { struct node *new = (struct node *) malloc(sizeof(struct node)); + if (!new) { + return 0; + } + insert_snake_node(new); + return 1; } int snake_has_eaten(int apple_x, int apple_y) diff --git a/snake.h b/snake.h index e31aae8..13225b1 100644 --- a/snake.h +++ b/snake.h @@ -13,11 +13,11 @@ enum direction { extern queue snake; extern int snake_dir; -void init_snake(void); +int init_snake(void); void empty_snake(void); void update_snake(void); void turn_snake(int direction, int opposite, int *dir_changed); -void grow_snake(void); +int grow_snake(void); void insert_snake_node(struct node *new); int snake_has_eaten(int apple_x, int apple_y); int check_snake_location(int arena_Width, int arena_height);