From 92ad1e1c31f45249c25638e54b6a5dc5a5e3245c Mon Sep 17 00:00:00 2001 From: Simon Wiesend <117300309+smnws@users.noreply.github.com> Date: Fri, 21 Nov 2025 09:09:55 +0100 Subject: [PATCH] clean up and improve allocation error handling --- matrix.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/matrix.c b/matrix.c index 0aaaae3..cf75a94 100644 --- a/matrix.c +++ b/matrix.c @@ -1,6 +1,7 @@ #include #include #include "matrix.h" +#include Matrix createMatrix(unsigned int rows, unsigned int cols) { @@ -20,6 +21,7 @@ Matrix createMatrix(unsigned int rows, unsigned int cols) if (mat.buffer == NULL) { clearMatrix(&mat); + perror("could not allocate memory"); } return mat; @@ -60,6 +62,11 @@ Matrix add(const Matrix matrix1, const Matrix matrix2) { Matrix resMat = (matrix1.cols > matrix2.cols) ? createMatrix(matrix1.rows, matrix1.cols) : createMatrix(matrix2.rows, matrix2.cols); + if (resMat.buffer == NULL) + { + return createMatrix(0, 0); + } + if (matrix1.cols != matrix2.cols) { if (matrix1.rows != matrix2.rows) @@ -110,7 +117,6 @@ Matrix add(const Matrix matrix1, const Matrix matrix2) return resMat; } -// TODO implement Matrix multiply(const Matrix matrix1, const Matrix matrix2) { if (matrix1.cols != matrix2.rows || matrix1.buffer == NULL || matrix2.buffer == NULL) @@ -121,6 +127,11 @@ Matrix multiply(const Matrix matrix1, const Matrix matrix2) int rows = matrix1.rows, cols = matrix2.cols; Matrix resMat = createMatrix(rows, cols); + if (resMat.buffer == NULL) + { + return createMatrix(0, 0); + } + for (size_t rowIdx = 0; rowIdx < rows; rowIdx++) { for (size_t colIdx = 0; colIdx < cols; colIdx++)