From 55603bf12c464ac5dc118c74bdb4b3b75fafb6bc Mon Sep 17 00:00:00 2001 From: Sara Date: Sun, 16 Nov 2025 14:37:24 +0100 Subject: [PATCH] clearmatrix & matrix add korrigiert -> tests runnen --- matrix.c | 52 +++++++++++++++++++++++++++++++--------------------- 1 file changed, 31 insertions(+), 21 deletions(-) diff --git a/matrix.c b/matrix.c index 78df5aa..bab79e5 100644 --- a/matrix.c +++ b/matrix.c @@ -28,10 +28,18 @@ Matrix createMatrix(unsigned int rows, unsigned int cols) void clearMatrix(Matrix *matrix) { - free(matrix->buffer); //gibt den heap speicher frei - matrix->buffer = NULL; //zeiger auf NULL setzen - matrix->rows = 0; - matrix->cols = 0; + // Sicherheits-Check für den übergebenen Zeiger + if (matrix != NULL) + { + // **WICHTIGE KORREKTUR:** Puffer-Check vor free() + if (matrix->buffer != NULL) { + free(matrix->buffer); + } + + matrix->buffer = NULL; // Zeiger auf NULL setzen + matrix->rows = 0; + matrix->cols = 0; + } } void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx) @@ -55,30 +63,32 @@ Matrix add(const Matrix matrix1, const Matrix matrix2) if (matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols) { - Matrix result; - result.rows = 0; - result.cols = 0; - result.buffer = NULL; - return result; + Matrix result = {0}; // Struktur auf 0/NULL initialisieren + result.rows = 0; + result.cols = 0; + result.buffer = NULL; + return result; } else { - //Matrix result ist die neue Matrix für das Ergebnis - Matrix result; - result.rows = matrix1.rows; - result.cols = matrix1.cols; - //TODO: Chat sagt hier noch buffer calloc rein + // **WICHTIGE KORREKTUR:** Speicher für das Ergebnis reservieren + Matrix result = createMatrix(matrix1.rows, matrix1.cols); + // Prüfen, ob Speicherreservierung erfolgreich war + if (result.buffer == NULL) { + return result; // Gibt Null-Matrix zurück, falls malloc fehlschlug + } - //Addition der beiden Matrizen - for (int i = 0; i < result.rows * result.cols; i++) - { - result.buffer[i] = matrix1.buffer[i] + matrix2.buffer[i]; + // Addition der beiden Matrizen + for (unsigned int i = 0; i < result.rows * result.cols; i++) + { + // Achtung: Wenn Sie die Matrizen nicht per const Pointer übergeben, + // müssen Sie wissen, dass die Daten nicht temporär sind (hier ok, da lokale Kopien). + result.buffer[i] = matrix1.buffer[i] + matrix2.buffer[i]; + } - } - - return result; + return result; }