From bd39c6ab8b87a90944afe271ce847ed0ce090c92 Mon Sep 17 00:00:00 2001 From: Jasper Date: Mon, 8 Sep 2025 10:28:01 +0200 Subject: Used calloc instead of alloc Calloc initializes the elements with 0 instead of possibly undefined behavior. 'matrix_const(..., ..., 0)' is not needed anymore --- matrix.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'matrix.c') diff --git a/matrix.c b/matrix.c index cdb50ad..2a5cff1 100644 --- a/matrix.c +++ b/matrix.c @@ -10,7 +10,7 @@ Matrix *matrix_alloc(size_t m, size_t n) { - double *xs = malloc(m * n * sizeof(double)); + double *xs = calloc(m * n, sizeof(double)); assert(xs != NULL && "Allocation of matrix elements failed"); Matrix *mat = malloc(sizeof(Matrix)); assert(mat != NULL && "Allocation of matrix failed"); @@ -59,7 +59,7 @@ Matrix *matrix_from_str(char *str) size_t rows = str_count_occ(str, ';') + 1; size_t cols = (str_count_occ(str, ' ') + rows) / rows; - Matrix *mat_tmp = matrix_const(rows, cols, 0); + Matrix *mat_tmp = matrix_alloc(rows, cols); for (size_t i = 0; (row = strsep(&str, ";")); ++i) { @@ -90,7 +90,7 @@ char *matrix_to_str(const Matrix *mat) Matrix *matrix_id(size_t n) { - Matrix *tmp = matrix_const(n, n, 0); + Matrix *tmp = matrix_alloc(n, n); for (size_t i = 0; i < n; ++i) matrix_at(tmp, i, i) = 1; @@ -235,7 +235,7 @@ void matrix_sub1(Matrix *A, const Matrix *B) Matrix *matrix_mult(const Matrix *A, const Matrix *B) { assert(A->n == B->m && "Dimension mismatch"); - Matrix *C = matrix_const(A->m, B->n, 0); + Matrix *C = matrix_alloc(A->m, B->n); matrix_foreach_idx(C, c, i, j) { for (size_t k = 0; k < A->n; ++k) @@ -294,7 +294,7 @@ Matrix **matrix_LR(const Matrix *A, const Matrix *b) Matrix *L = matrix_id(A->n); Matrix *A_prev = matrix_copy(A); - Matrix *A_curr = matrix_const(A->n, A->n, 0); + Matrix *A_curr = matrix_alloc(A->n, A->n); for (size_t k = 1; k < A->n; ++k) { @@ -317,7 +317,7 @@ Matrix **matrix_LR(const Matrix *A, const Matrix *b) A_prev = matrix_copy(A_curr); if (k != A->n - 1) - A_curr = matrix_const(A->n, A->n, 0); + A_curr = matrix_alloc(A->n, A->n); } matrix_free(A_prev); @@ -334,7 +334,7 @@ Matrix *matrix_forwardel(const Matrix *L, const Matrix *b) assert(matrix_is_colvec(b) && "Column vector b expected"); double sum; - Matrix *y = matrix_const(L->n, 1, 0); + Matrix *y = matrix_alloc(L->n, 1); for (size_t i = 0; i < y->m; ++i) { @@ -351,7 +351,7 @@ Matrix *matrix_backsubst(const Matrix *R, const Matrix *y) { assert(R->n == y->m && "Dimension mismatch"); assert(matrix_is_colvec(y) && "Column vector y expected"); - Matrix *x = matrix_const(R->n, 1, 0); + Matrix *x = matrix_alloc(R->n, 1); double sum; -- cgit v1.2.3