From fc9ae26aacede490d32f0b31d314f2c8286d158a Mon Sep 17 00:00:00 2001 From: Frederick Yin Date: Mon, 6 Jun 2022 11:36:51 +0800 Subject: Exit if malloc() fails --- pieces.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'pieces.c') diff --git a/pieces.c b/pieces.c index f1ed17c..3b71003 100644 --- a/pieces.c +++ b/pieces.c @@ -2,6 +2,7 @@ #include #include #include "pieces.h" +#include "util.h" const int N_SHAPES = 17; const struct piece SHAPES[] = { @@ -27,6 +28,9 @@ const struct piece SHAPES[] = { void transpose(struct piece* pc) { // transpose blocks char* old = malloc(strlen(pc->blocks) + 1); + if (old == NULL) + mallocfail(); + strcpy(old, pc->blocks); // before transposition for (int r = 0; r < pc->h; r++) { for (int c = 0; c < pc->w; c++) { @@ -44,6 +48,9 @@ void rotate(struct piece* pc) { // rotate `pc` ccw by 90 degrees // transpose blocks char* old = malloc(strlen(pc->blocks) + 1); + if (old == NULL) + mallocfail(); + strcpy(old, pc->blocks); // before transposition for (int r = 0; r < pc->h; r++) { for (int c = 0; c < pc->w; c++) { @@ -62,8 +69,14 @@ struct piece* randpiece() { // then do random transformations to the copy struct piece shape = SHAPES[rand() % N_SHAPES]; char* blocks = malloc(strlen(shape.blocks) + 1); + if (blocks == NULL) + mallocfail(); + strcpy(blocks, shape.blocks); struct piece* pc = malloc(sizeof(struct piece)); + if (pc == NULL) + mallocfail(); + pc->h = shape.h; pc->w = shape.w; pc->points = shape.points; -- cgit v1.2.3