summaryrefslogtreecommitdiff
path: root/pieces.c
diff options
context:
space:
mode:
authorFrederick Yin <fkfd@fkfd.me>2022-06-06 11:36:51 +0800
committerFrederick Yin <fkfd@fkfd.me>2022-06-06 11:36:51 +0800
commitfc9ae26aacede490d32f0b31d314f2c8286d158a (patch)
treee47a27c91f38c4ae2b54dfca691b96cc7b62168f /pieces.c
parent6e945b3f487d92d3cdf8706164da7040b9cb375a (diff)
Exit if malloc() fails
Diffstat (limited to 'pieces.c')
-rw-r--r--pieces.c13
1 files changed, 13 insertions, 0 deletions
diff --git a/pieces.c b/pieces.c
index f1ed17c..3b71003 100644
--- a/pieces.c
+++ b/pieces.c
@@ -2,6 +2,7 @@
#include <stdbool.h>
#include <string.h>
#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;