Skip to content
The Chat Archive
gpt-4-turbo-2024-04-09· OpenAI WildChat-4.8M (AI2)

#include "../s21matrix.h" int s21creatematrix(int rows, int columns, matrixt *result) {…

  1. User

    #include "../s21_matrix.h"

    int s21_create_matrix(int rows, int columns, matrix_t *result) { if (result == NULL) return ERROR_INIT;

    int matrix_status = OK;

    if (rows < 1 || columns < 1) { matrix_status = ERROR_INIT; result->matrix = NULL; } else { result->rows = rows; result->columns = columns; result->matrix = (double **)calloc(rows, sizeof(double *)); if (result->matrix == NULL) { matrix_status = ERROR_INIT; } else { for (int i = 0; i < rows; i++) { result->matrix[i] = (double *)calloc(columns, sizeof(double)); if (result->matrix[i] == NULL) { matrix_status = ERROR_CALC; s21_remove_matrix(result); } } } }

    return matrix_status; } #include "../s21_matrix.h"

    void s21_remove_matrix(matrix_t *A) { if (A != NULL && A->matrix != NULL) { for (int i = 0; i < A->rows; ++i) { free(A->matrix[i]); } free(A->matrix); A->matrix = NULL; A->columns = 0; A->rows = 0; } } #include "../s21_matrix.h"

    int s21_inverse_matrix(matrix_t *A, matrix_t *result) { if (A == NULL || A->matrix == NULL || result == NULL) { return ERROR_INIT; } if (A->columns != A->rows) return ERROR_CALC;

    int status = OK; status = s21_create_matrix(A->rows, A->columns, result);

    if (status == OK) { double det; status = s21_determinant(A, &det); if (status == OK) { if (det == 0) return ERROR_CALC; matrix_t transpose_complements; status = s21_adj_matrix(A, &transpose_complements); if (status == OK) { status = s21_mult_number(&transpose_complements, 1 / det, result); } s21_remove_matrix(&transpose_complements); } }

    return status; } #include "../s21_matrix.h"

    int s21_determinant(matrix_t *A, double *result) { if (A == NULL || A->matrix == NULL || result == NULL) { return ERROR_INIT; }

    if (A->columns != A->rows) { return ERROR_CALC; }

    int status = OK; if (A->rows == 1) { *result = A->matrix[0][0]; } else if (A->rows == 2) { *result = A->matrix[0][0] * A->matrix[1][1] - A->matrix[0][1] * A->matrix[1][0]; } else { double det = 0.0; for (int i = 0; i < A->rows; ++i) { matrix_t minor_matrix; status = s21_minor_matrix(A, 0, i, &minor_matrix); if (status != OK) { return ERROR_CALC; } double minor_det; status = s21_determinant(&minor_matrix, &minor_det); if (status != OK) { return ERROR_CALC; } if (i % 2 == 0) { det += A->matrix[0][i] * minor_det; } else { det -= A->matrix[0][i] * minor_det; } s21_remove_matrix(&minor_matrix); } *result = det; } return status; } #include "../s21_matrix.h"

    void s21_initialize_matrix(matrix_t *A, double start_value, double iteration_step) { if (A != NULL && A->matrix != NULL) { double value = start_value; for (int i = 0; i < A->rows; i++) { for (int j = 0; j < A->columns; j++) { A->matrix[i][j] = value; value += iteration_step; } } } }

    int s21_minor_matrix(matrix_t *A, int rows, int columns, matrix_t *result) { if (A == NULL || A->matrix == NULL || result == NULL) { return ERROR_INIT; }

    int status = OK; status = s21_create_matrix(A->rows - 1, A->columns - 1, result);

    if (status == OK) { int new_row = 0; for (int i = 0; i < A->rows; ++i) { if (i == rows) { continue; }

      int new_col = 0;
      for (int j = 0; j < A->columns; ++j) {
        if (j == columns) {
          continue;
        }
    
        result->matrix[new_row][new_col] = A->matrix[i][j];
        new_col++;
      }
      new_row++;
    }
    

    } return status; }

    int s21_adj_matrix(matrix_t *A, matrix_t *result) { if (A == NULL || A->matrix == NULL || result == NULL) { return ERROR_INIT; }

    int status = OK; status = s21_create_matrix(A->rows, A->columns, result);

    if (status == OK) { matrix_t complements_matrix; status = s21_calc_complements(A, &complements_matrix); if (status == OK) { status = s21_transpose(&complements_matrix, result); } s21_remove_matrix(&complements_matrix); } return status; } #include "../s21_matrix.h"

    int s21_mult_number(matrix_t *A, double number, matrix_t *result) { if (A == NULL || A->matrix == NULL || result == NULL) { return ERROR_INIT; }

    if (A->rows < 1 || A->columns < 1 || !isfinite(number)) { return ERROR_CALC; } int status = OK; status = s21_create_matrix(A->rows, A->columns, result); if (!status) { for (int i = 0; i < A->rows && status == OK; ++i) { for (int j = 0; j < A->columns && status == OK; ++j) { result->matrix[i][j] = A->matrix[i][j] * number; if (!isfinite(result->matrix[i][j])) { status = ERROR_CALC; } } } } return status; } #include "s21_matrix_test.h"

    START_TEST(test_inverse_matrix_0) { matrix_t A = {}; matrix_t result = {}; ck_assert_int_eq(s21_inverse_matrix(&A, &result), ERROR_INIT); s21_remove_matrix(&A); s21_remove_matrix(&result); } END_TEST

    START_TEST(test_inverse_matrix_1) { matrix_t A = {}; matrix_t result = {}; s21_create_matrix(3, 3, &A); s21_initialize_matrix(&A, 1, 1); ck_assert_int_eq(s21_inverse_matrix(&A, &result), ERROR_CALC); s21_remove_matrix(&A); s21_remove_matrix(&result); } END_TEST

    START_TEST(test_inverse_matrix_2) { matrix_t A = {}; matrix_t result = {}; s21_create_matrix(5, 3, &A); s21_initialize_matrix(&A, 1, 1); ck_assert_int_eq(s21_inverse_matrix(&A, &result), ERROR_CALC); s21_remove_matrix(&A); s21_remove_matrix(&result); } END_TEST

    START_TEST(test_inverse_matrix_3) { matrix_t A = {}; matrix_t result = {}; matrix_t eq_matrix = {}; s21_create_matrix(1, 1, &A); s21_create_matrix(1, 1, &eq_matrix); A.matrix[0][0] = 21; eq_matrix.matrix[0][0] = 1.0 / 21.0; ck_assert_int_eq(s21_inverse_matrix(&A, &result), OK); s21_remove_matrix(&A); ck_assert_int_eq(s21_eq_matrix(&result, &eq_matrix), SUCCESS); s21_remove_matrix(&result); s21_remove_matrix(&eq_matrix); } END_TEST

    START_TEST(test_inverse_matrix_4) { matrix_t A = {}; matrix_t result = {}; matrix_t eq_matrix = {}; s21_create_matrix(3, 3, &A); s21_create_matrix(3, 3, &eq_matrix); A.matrix[0][0] = 2, A.matrix[0][1] = 5, A.matrix[0][2] = 7; A.matrix[1][0] = 6, A.matrix[1][1] = 3, A.matrix[1][2] = 4; A.matrix[2][0] = 5, A.matrix[2][1] = -2, A.matrix[2][2] = -3; eq_matrix.matrix[0][0] = 1, eq_matrix.matrix[0][1] = -1, eq_matrix.matrix[0][2] = 1; eq_matrix.matrix[1][0] = -38, eq_matrix.matrix[1][1] = 41, eq_matrix.matrix[1][2] = -34; eq_matrix.matrix[2][0] = 27, eq_matrix.matrix[2][1] = -29, eq_matrix.matrix[2][2] = 24; ck_assert_int_eq(s21_inverse_matrix(&A, &result), OK); ck_assert_int_eq(s21_eq_matrix(&result, &eq_matrix), SUCCESS); s21_remove_matrix(&A); s21_remove_matrix(&result); s21_remove_matrix(&eq_matrix); } END_TEST

    START_TEST(test_inverse_matrix_5) { int res = 0; matrix_t A = {0}; matrix_t Z = {0}; matrix_t X = {0};

    s21_create_matrix(4, 4, &A); A.matrix[0][0] = -1.0; A.matrix[0][1] = 2.0; A.matrix[0][2] = 7.0; A.matrix[0][3] = 9.0; A.matrix[1][0] = 1.0; A.matrix[1][1] = 0.0; A.matrix[1][2] = 0.0; A.matrix[1][3] = 0.0; A.matrix[2][0] = 47.0; A.matrix[2][1] = 13.0; A.matrix[2][2] = 17.0; A.matrix[2][3] = 21.0; A.matrix[3][0] = 22.0; A.matrix[3][1] = 7.0; A.matrix[3][2] = 1.0; A.matrix[3][3] = 3.0;

    s21_inverse_matrix(&A, &Z); s21_remove_matrix(&A); s21_create_matrix(4, 4, &X);

    X.matrix[0][0] = 0.0; X.matrix[0][1] = 1.0; X.matrix[0][2] = 0.0; X.matrix[0][3] = 0.0; X.matrix[1][0] = -5.0 / 23.0; X.matrix[1][1] = -121.0 / 23.0; X.matrix[1][2] = 2.0 / 23.0; X.matrix[1][3] = 1.0 / 23.0; X.matrix[2][0] = -18.0 / 23.0; X.matrix[2][1] = -379.0 / 46.0; X.matrix[2][2] = 19.0 / 46.0; X.matrix[2][3] = -25.0 / 46.0; X.matrix[3][0] = 53.0 / 69.0; X.matrix[3][1] = 1061.0 / 138.0; X.matrix[3][2] = -47.0 / 138.0; X.matrix[3][3] = 19.0 / 46.0;

    res = s21_eq_matrix(&X, &Z);

    s21_remove_matrix(&X); s21_remove_matrix(&Z);

    ck_assert_int_eq(res, SUCCESS); } END_TEST

    START_TEST(test_inverse_matrix_6) { int res; matrix_t A = {0}; matrix_t Z = {0};

    s21_create_matrix(1, 1, &A); A.matrix[0][0] = 2;

    res = s21_inverse_matrix(&A, &Z);

    ck_assert_int_eq(Z.matrix[0][0] == (1.0 / A.matrix[0][0]), 1); ck_assert_int_eq(res, OK);

    s21_remove_matrix(&A); s21_remove_matrix(&Z); } END_TEST

    START_TEST(test_inverse_matrix_7) { int res = 0; matrix_t A = {0}; matrix_t Z = {0};

    s21_create_matrix(3, 3, &A); s21_initialize_matrix(&A, 1.0, 1);

    res = s21_inverse_matrix(&A, &Z); ck_assert_int_eq(res, ERROR_CALC); s21_remove_matrix(&A); s21_remove_matrix(&Z); } END_TEST

    START_TEST(test_inverse_matrix_8) { int res = 0; matrix_t A = {0}; matrix_t Z = {0};

    s21_create_matrix(3, 2, &A); s21_initialize_matrix(&A, 1.0, 1);

    res = s21_inverse_matrix(&A, &Z); ck_assert_int_eq(res, ERROR_CALC); s21_remove_matrix(&A); s21_remove_matrix(&Z); } END_TEST

    START_TEST(test_inverse_matrix_9) { int res = 0; matrix_t A = {0}; matrix_t Z = {0};

    s21_create_matrix(3, 3, &A); s21_initialize_matrix(&A, 1.0, 1); s21_remove_matrix(&A);

    res = s21_inverse_matrix(&A, &Z);

    ck_assert_int_eq(res, ERROR_INIT); s21_remove_matrix(&Z); } END_TEST

    START_TEST(test_inverse_matrix_10) { int res = 0; matrix_t A = {0}; matrix_t Z = {0}; matrix_t X = {0};

    s21_create_matrix(3, 3, &A); A.matrix[0][0] = 1.0; A.matrix[0][1] = 2.0; A.matrix[0][2] = 3.0; A.matrix[1][0] = 4.0; A.matrix[1][1] = 5.0; A.matrix[1][2] = 6.0; A.matrix[2][0] = 8.0; A.matrix[2][1] = 6.0; A.matrix[2][2] = 9.0;

    s21_inverse_matrix(&A, &Z);

    s21_create_matrix(3, 3, &X);

    X.matrix[0][0] = -3.0 / 5.0; X.matrix[0][1] = 0.0; X.matrix[0][2] = 1.0 / 5.0; X.matrix[1][0] = -4.0 / 5.0; X.matrix[1][1] = 1.0; X.matrix[1][2] = -2.0 / 5.0; X.matrix[2][0] = 16.0 / 15.0; X.matrix[2][1] = -2.0 / 3.0; X.matrix[2][2] = 1.0 / 5.0;

    res = s21_eq_matrix(&X, &Z); s21_remove_matrix(&A); s21_remove_matrix(&X); s21_remove_matrix(&Z);

    ck_assert_int_eq(res, SUCCESS); } END_TEST

    Suite* suite_inverse_matrix(void) { Suite* s = suite_create("suite_inverse_matrix"); TCase* tc = tcase_create("case_inverse_matrix");

    tcase_add_test(tc, test_inverse_matrix_0); tcase_add_test(tc, test_inverse_matrix_1); tcase_add_test(tc, test_inverse_matrix_2); tcase_add_test(tc, test_inverse_matrix_3); tcase_add_test(tc, test_inverse_matrix_4); tcase_add_test(tc, test_inverse_matrix_5); tcase_add_test(tc, test_inverse_matrix_6); tcase_add_test(tc, test_inverse_matrix_7); tcase_add_test(tc, test_inverse_matrix_8); tcase_add_test(tc, test_inverse_matrix_9); tcase_add_test(tc, test_inverse_matrix_10);

    suite_add_tcase(s, tc); return s; }

    ==231467== ==231467== 16 (8 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 5 of 22 ==231467== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==231467== by 0x11ECC1: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==231467== by 0x11F3B0: s21_inverse_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==231467== by 0x1123EA: test_inverse_matrix_3_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out)

  2. Assistant

    The reported memory leak occurs during the s21_inverse_matrix function call during test_inverse_matrix_3_fn. The leak is traced back to the allocation made in s21_create_matrix. Here is a breakdown of the relevant code and where the mistake might be:

    1. Memory Allocation in s21_create_matrix:

      • Memory for the matrix structure (including the individual rows) is allocated using calloc, which also initializes the allocated memory to zero.
    2. Memory Freeing using s21_remove_matrix:

      • All memory that is allocated for the matrix and its individual rows is supposed to be freed in s21_remove_matrix.
    3. Potential Memory Leak Causes:

      • The memory leak is indicated to be associated directly with memory that was allocated in s21_create_matrix and meant to be cleaned up after being used in s21_inverse_matrix.
      • The possible issue here looks like either: a. A path exists in s21_inverse_matrix that results in the result matrix being allocated (using s21_create_matrix) but not properly cleaned up on all paths (for example, when an intermediate error occurs and function exits prematurely without freeing allocated matrix). b. The s21_remove_matrix is not properly called or executed for some of the matrices that are created during the process (such as temporary or intermediate matrices).
      • If errors like ERROR_CALC trigger an early exit from the function without the needed cleanup, this could cause a leak.
    4. Valgrind Report:

      • The report claims 16 bytes are lost, corresponding perhaps to several matrix rows, indicating that the matrix, or parts of it, are not completely freed.

    To rectify this, ensure that:

    • There are corresponding s21_remove_matrix calls for all matrices created with s21_create_matrix in every path through the code including error paths.
    • Review and check every return path after a matrix creation inside s21_inverse_matrix to ensure all matrices are either passed onwards properly or cleaned up.

    Here’s a modification to s21_inverse_matrix to potentially fix the leak:

    int s21_inverse_matrix(matrix_t *A, matrix_t *result) {
      if (A == NULL || A->matrix == NULL || result == NULL) {
        return ERROR_INIT;
      }
      if (A->columns != A->rows) return ERROR_CALC;
    
      int status = OK;
      status = s21_create_matrix(A->rows, A->columns, result);
    
      if (status == OK) {
        double det;
        matrix_t transpose_complements;
        int comp_created = s21_create_matrix(A->rows, A->rows, &transpose_complements);
        if (comp_created == OK) {
          status = s21_determinant(A, &det);
          if (status == OK && det != 0) {
            status = s21_adj_matrix(A, &transpose_complements);
            if (status == OK) {
              status = s21_mult_number(&transpose_complements, 1 / det, result);
            }
          } else {
            status = ERROR_CALC;
          }
          s21_remove_matrix(&transpose_complements);
        } else {
          status = ERROR_INIT;
        }
        if (status != OK) {
          s21_remove_matrix(result);
        }
      }
      return status;
    }
    

    This coding ensures proper cleanup even if there is an error after matrix creation. This includes removing the created matrix on error before exiting the function.

    Also, check similar practices in other functions calling s21_create_matrix.

  3. User

    объясни на русском что написано и где утечки ==234250== ==234250== HEAP SUMMARY: ==234250== in use at exit: 888 bytes in 38 blocks ==234250== total heap usage: 104,508 allocs, 104,470 frees, 15,964,555 bytes allocated ==234250== ==234250== 16 (8 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 5 of 22 ==234250== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==234250== by 0x11ECC1: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F3B0: s21_inverse_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x1123EA: test_inverse_matrix_3_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122690: tcase_run_tfun_nofork (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122B6E: srunner_run_tagged (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11391C: run_testcase (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11388F: run_tests (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x113938: main (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== ==234250== 16 (8 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 6 of 22 ==234250== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==234250== by 0x11ECC1: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F2CB: s21_adj_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F40C: s21_inverse_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x1123EA: test_inverse_matrix_3_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122690: tcase_run_tfun_nofork (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122B6E: srunner_run_tagged (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11391C: run_testcase (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11388F: run_tests (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x113938: main (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== ==234250== 16 (8 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 7 of 22 ==234250== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==234250== by 0x11ECC1: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F3B0: s21_inverse_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x112DA2: test_inverse_matrix_6_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122690: tcase_run_tfun_nofork (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122B6E: srunner_run_tagged (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11391C: run_testcase (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11388F: run_tests (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x113938: main (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== ==234250== 16 (8 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 8 of 22 ==234250== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==234250== by 0x11ECC1: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F2CB: s21_adj_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F40C: s21_inverse_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x112DA2: test_inverse_matrix_6_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122690: tcase_run_tfun_nofork (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122B6E: srunner_run_tagged (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11391C: run_testcase (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11388F: run_tests (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x113938: main (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== ==234250== 96 (24 direct, 72 indirect) bytes in 1 blocks are definitely lost in loss record 14 of 22 ==234250== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==234250== by 0x11ECC1: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F3B0: s21_inverse_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x112775: test_inverse_matrix_4_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122690: tcase_run_tfun_nofork (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122B6E: srunner_run_tagged (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11391C: run_testcase (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11388F: run_tests (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x113938: main (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== ==234250== 96 (24 direct, 72 indirect) bytes in 1 blocks are definitely lost in loss record 15 of 22 ==234250== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==234250== by 0x11ECC1: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F2CB: s21_adj_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F40C: s21_inverse_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x112775: test_inverse_matrix_4_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122690: tcase_run_tfun_nofork (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122B6E: srunner_run_tagged (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11391C: run_testcase (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11388F: run_tests (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x113938: main (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== ==234250== 96 (24 direct, 72 indirect) bytes in 1 blocks are definitely lost in loss record 16 of 22 ==234250== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==234250== by 0x11ECC1: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F3B0: s21_inverse_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x113426: test_inverse_matrix_10_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122690: tcase_run_tfun_nofork (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122B6E: srunner_run_tagged (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11391C: run_testcase (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11388F: run_tests (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x113938: main (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== ==234250== 96 (24 direct, 72 indirect) bytes in 1 blocks are definitely lost in loss record 17 of 22 ==234250== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==234250== by 0x11ECC1: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F2CB: s21_adj_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F40C: s21_inverse_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x113426: test_inverse_matrix_10_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122690: tcase_run_tfun_nofork (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122B6E: srunner_run_tagged (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11391C: run_testcase (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11388F: run_tests (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x113938: main (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== ==234250== 120 (24 direct, 96 indirect) bytes in 1 blocks are definitely lost in loss record 18 of 22 ==234250== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==234250== by 0x11ECC1: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11E3E9: test_transpose_6_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122690: tcase_run_tfun_nofork (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122B6E: srunner_run_tagged (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11391C: run_testcase (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11388F: run_tests (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x113938: main (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== ==234250== 160 (32 direct, 128 indirect) bytes in 1 blocks are definitely lost in loss record 21 of 22 ==234250== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==234250== by 0x11ECC1: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F3B0: s21_inverse_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x112ABF: test_inverse_matrix_5_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122690: tcase_run_tfun_nofork (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122B6E: srunner_run_tagged (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11391C: run_testcase (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11388F: run_tests (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x113938: main (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== ==234250== 160 (32 direct, 128 indirect) bytes in 1 blocks are definitely lost in loss record 22 of 22 ==234250== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==234250== by 0x11ECC1: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F2CB: s21_adj_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11F40C: s21_inverse_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x112ABF: test_inverse_matrix_5_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122690: tcase_run_tfun_nofork (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x122B6E: srunner_run_tagged (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11391C: run_testcase (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x11388F: run_tests (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== by 0x113938: main (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==234250== ==234250== LEAK SUMMARY: ==234250== definitely lost: 216 bytes in 11 blocks ==234250== indirectly lost: 672 bytes in 27 blocks ==234250== possibly lost: 0 bytes in 0 blocks ==234250== still reachable: 0 bytes in 0 blocks ==234250== suppressed: 0 bytes in 0 blocks ==234250== ==234250== For lists of detected and suppressed errors, rerun with: -s ==234250== ERROR SUMMARY: 11 errors from 11 contexts (suppressed: 0 from 0)

  4. Assistant

    Отчет Valgrind указывает на утечки памяти в вашем коде. Утечки происходят при вызовах функций s21_create_matrix, s21_adj_matrix и s21_inverse_matrix. В каждом случае создаются объекты (матрицы), для которых выделяется память, но эта память не всегда корректно освобождается. Вот как это можно понимать:

    Описание утечек:

    • В 11 блоках (общий прямой ущерб 216 байт и косвенный ущерб 672 байта) память выделяется, но не освобождается, что ведет к утечкам. Эти утечки распределены между различными тестами, в каждом из которых задействованы упомянутые функции.

    Причины утечек:

    • Выделение памяти с помощью calloc: Valgrind указывает на вызовы calloc внутри функции s21_create_matrix, где происходит инициализация матрицы. Если после создания матрицы возникает ошибка или функция завершается по какой-то причине без должного очищения памяти, это приводит к утечке.
    • Функция s21_adj_matrix: В этой функции создается матрица смежности, которая также требует памяти. Если после создания смежной матрицы функция завершается досрочно или без корректного удаления этой матрицы, это также может привести к утечкам.
    • Функция s21_inverse_matrix: Эта функция вызывает другие функции по созданию матриц (например, s21_create_matrix и s21_adj_matrix). Утечки могут возникнуть, если после создания этих матриц память не освобождается в случае ошибок или когда матрицы больше не нужны, но не удалены.

    Решение проблемы:

    • Удостовериться, что для каждой успешно созданной матрицы вызывается s21_remove_matrix, которая освобождает всю выделенную память, во всех возможных путях исполнения кода (включая случаи ошибок).
    • Проверить, правильно ли обрабатываются ошибки после каждого вызова функций создания матриц. Если функция возвращает ошибку, нужно убедиться, что перед выходом из функции выполняется очистка всех созданных на этом этапе ресурсов.

    Дальнейшие шаги:

    • Добавить в код обработки ошибок и удаления матриц после их использования во всех ветках исполнения, особенно после обработки исключений или ошибочных сценариев.
    • Использовать инструменты, такие как Valgrind, для повторной проверки, успешно ли были устранены утечки после внесения изменений в код.
  5. User

    исправь сам утечки int s21_create_matrix(int rows, int columns, matrix_t *result) { if (result == NULL) return ERROR_INIT;

    int matrix_status = OK;

    if (rows < 1 || columns < 1) { matrix_status = ERROR_INIT; result->matrix = NULL; } else { result->rows = rows; result->columns = columns; result->matrix = (double **)calloc(rows, sizeof(double *)); if (result->matrix == NULL) { matrix_status = ERROR_INIT; } else { for (int i = 0; i < rows; i++) { result->matrix[i] = (double *)calloc(columns, sizeof(double)); if (result->matrix[i] == NULL) { matrix_status = ERROR_CALC; s21_remove_matrix(result); } } } }

    return matrix_status; }

  6. Assistant

    Чтобы исправить утечки памяти в функции s21_create_matrix, необходимо обеспечить, что если в процессе создания матрицы происходит ошибка после выделения памяти для одной из строк, следует правильно очистить уже выделенную память для предыдущих строк и самой матрицы. Данные некорректные действия могли привести к утечкам, о которых сообщал Valgrind.

    Вот исправленная версия функции s21_create_matrix, которая гарантирует освобождение всех ресурсов в случае ошибки:

    #include <stdlib.h>  // Для использования calloc и free
    #include <stdio.h>
    
    #define OK 0
    #define ERROR_INIT 1
    #define ERROR_CALC 2
    
    typedef struct {
        int rows, columns;
        double **matrix;
    } matrix_t;
    
    // Функция для удаления матрицы
    void s21_remove_matrix(matrix_t *A) {
        if (A != NULL && A->matrix != NULL) {
            for (int i = 0; i < A->rows; i++) {
                free(A->matrix[i]);  // Чистим каждую строку
            }
            free(A->matrix);  // Чистим массив указателей
            A->matrix = NULL;
            A->columns = 0;
            A->rows = 0;
        }
    }
    
    // Функция для создания матрицы
    int s21_create_matrix(int rows, int columns, matrix_t *result) {
        if (result == NULL) return ERROR_INIT;
        result->matrix = NULL;
    
        int matrix_status = OK;
        if (rows < 1 || columns < 1) {
            matrix_status = ERROR_INIT;
        } else {
            result->rows = rows;
            result->columns = columns;
            result->matrix = (double **)calloc(rows, sizeof(double *));
            if (result->matrix == NULL) {
                matrix_status = ERROR_INIT;
            } else {
                for (int i = 0; i < rows; i++) {
                    result->matrix[i] = (double *)calloc(columns, sizeof(double));
                    if (result->matrix[i] == NULL) {
                        matrix_status = ERROR_CALC;
                        s21_remove_matrix(result);
                        break;  // Выходим из цикла, так как произошла ошибка
                    }
                }
            }
        }
    
        return matrix_status;
    }
    

    Теперь в функции s21_create_matrix:

    1. Если при выделении памяти для одной из строк возникает ошибка, функция s21_remove_matrix вызывается, чтобы освободить всю ранее выделенную память, и выполнение прекращается (используется break).

    Такой подход позволяет избежать утечек памяти при возникновении ошибок в процессе выполнения.

  7. User

    где утечка START_TEST(test_inverse_matrix_3) { matrix_t A = {}; matrix_t result = {}; matrix_t eq_matrix = {}; s21_create_matrix(1, 1, &A); s21_create_matrix(1, 1, &eq_matrix); A.matrix[0][0] = 21; eq_matrix.matrix[0][0] = 1.0 / 21.0; ck_assert_int_eq(s21_inverse_matrix(&A, &result), OK); s21_remove_matrix(&A); ck_assert_int_eq(s21_eq_matrix(&result, &eq_matrix), SUCCESS); s21_remove_matrix(&result); s21_remove_matrix(&eq_matrix); } END_TEST ==242237== ==242237== HEAP SUMMARY: ==242237== in use at exit: 32 bytes in 4 blocks ==242237== total heap usage: 103,885 allocs, 103,881 frees, 15,847,837 bytes allocated ==242237== ==242237== 16 (8 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 3 of 4 ==242237== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==242237== by 0x11D946: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x11E049: s21_inverse_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x1123EA: test_inverse_matrix_3_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x121330: tcase_run_tfun_nofork (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x12180E: srunner_run_tagged (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x11274D: run_testcase (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x1126C0: run_tests (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x112769: main (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== ==242237== 16 (8 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 4 of 4 ==242237== at 0x484DA83: calloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==242237== by 0x11D946: s21_create_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x11DF56: s21_adj_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x11E0A5: s21_inverse_matrix (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x1123EA: test_inverse_matrix_3_fn (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x121330: tcase_run_tfun_nofork (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x12180E: srunner_run_tagged (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x11274D: run_testcase (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x1126C0: run_tests (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== by 0x112769: main (in /home/fratello/school_21/C6_s21_matrix-1/src/s21_test.out) ==242237== ==242237== LEAK SUMMARY: ==242237== definitely lost: 16 bytes in 2 blocks ==242237== indirectly lost: 16 bytes in 2 blocks ==242237== possibly lost: 0 bytes in 0 blocks ==242237== still reachable: 0 bytes in 0 blocks ==242237== suppressed: 0 bytes in 0 blocks ==242237==

  8. Assistant

    Основываясь на вашем отчете Valgrind и исходном коде теста test_inverse_matrix_3, утечки памяти возникают в результате работы функций s21_create_matrix и s21_adj_matrix в контексте функции s21_inverse_matrix.

    Анализ утечек:

    1. Первая утечка (16 bytes в s21_create_matrix вызванная в s21_inverse_matrix):

      • Эта утечка происходит потому, что функция s21_inverse_matrix создает новую матрицу внутри себя (видимо для каких-то вычислений), и по какой-то причине эта матрица не освобождается должным образом. Вероятно, в s21_inverse_matrix не всегда вызывается s21_remove_matrix для очистки этой созданной матрицы при всех путях выполнения функции.
    2. Вторая утечка (16 bytes в s21_create_matrix через s21_adj_matrix, вызываемую в s21_inverse_matrix):

      • Как и в первом случае, s21_adj_matrix создает внутри себя матрицу и не удаляет её в случае всех возможных путей выполнения, что приводит к утечке.

    Решение:

    Чтобы исправить эти утечки, вам нужно убедиться, что все матрицы, созданные в s21_inverse_matrix и все вложенные вызовы функций, которые также создают матрицы, правильно удаляются в случае всех возможных путей выполнения (включая варианты с ошибками). Ниже предлагается возможный способ модификации s21_inverse_matrix, чтобы обеспечить корректное управление памятью:

    int s21_inverse_matrix(matrix_t *A, matrix_t *result) {
        int status = ERROR_INIT;
        if (A != NULL && A->matrix != NULL && result != NULL && A->columns == A->rows) {
            status = s21_create_matrix(A->rows, A->columns, result);
            if (status == OK) {
                double det = 0;
                if (s21_determinant(A, &det) == OK && det != 0) {
                    matrix_t adj = {0};
                    if (s21_adj_matrix(A, &adj) == OK) {
                        status = s21_mult_number(&adj, 1.0 / det, result);
                        s21_remove_matrix(&adj);
                    } else {
                        status = ERROR_CALC;
                        s21_remove_matrix(result);
                    }
                } else {
                    status = ERROR_CALC;
                    s21_remove_matrix(result);
                }
            }
        }
        return status;
    }
    

    Эта модификация добавляет недостающий вызов s21_remove_matrix для временной матрицы adj, а также удаляет результирующую матрицу в случае возникновения ошибок, что должно предотвратить обе утечки памяти.

  9. User

    не изменяй шаблон функции, просто добавь освобождение куда надо int s21_inverse_matrix(matrix_t *A, matrix_t *result) { if (A == NULL || A->matrix == NULL || result == NULL) { return ERROR_INIT; } if (A->columns != A->rows) return ERROR_CALC;

    int status = OK; status = s21_create_matrix(A->rows, A->columns, result);

    if (status == OK) { double det; status = s21_determinant(A, &det); matrix_t transpose_complements; if (status == OK) { if (det == 0) {

        return ERROR_CALC;
      }
      status = s21_adj_matrix(A, &transpose_complements);
      if (status == OK) {
        status = s21_mult_number(&transpose_complements, 1 / det, result);
      }
    }
    s21_remove_matrix(&transpose_complements);
    

    } else s21_remove_matrix(result);

    return status; }

  10. Assistant

    В вашем исходном коде функции s21_inverse_matrix уже правильно расставлены некоторые вызовы s21_remove_matrix для освобождения памяти в случае ошибок. Однако, вызов s21_remove_matrix(&transpose_complements); производится без проверки на то, была ли память для этой структуры (transpose_complements) действительно выделена. Это может приводить к попыткам освобождения памяти, которая не была выделена, если s21_adj_matrix вернул ошибку.

    Чтобы исправить это, нужно добавить проверку, что матрица transpose_complements действительно была создана, перед тем как освободить её. В вашем случае, также стоит учесть, что если при вызове s21_determinant либо при проверке детерминанта возникла ошибка, то s21_adj_matrix вызываться не будет, и transpose_complements не будет инициализирована. Правильный порядок освобождения выглядит так:

    int s21_inverse_matrix(matrix_t *A, matrix_t *result) {
      if (A == NULL || A->matrix == NULL || result == NULL) {
        return ERROR_INIT;
      }
      if (A->columns != A->rows) return ERROR_CALC;
    
      int status = OK;
      status = s21_create_matrix(A->rows, A->columns, result);
    
      if (status == OK) {
        double det;
        matrix_t transpose_complements = {0};
        status = s21_determinant(A, &det);
        if (status == OK) {
          if (det == 0) {
            s21_remove_matrix(result);
            return ERROR_CALC;
          }
          status = s21_adj_matrix(A, &transpose_complements);
          if (status == OK) {
            status = s21_mult_number(&transpose_complements, 1 / det, result);
          }
          s21_remove_matrix(&transpose_complements); // Удаляем только если `s21_adj_matrix` был вызван
        } else {
          s21_remove_matrix(result); // Удаляем если `s21_determinant` вернул ошибку
        }
      }
      return status;
    }
    

    Это изменение гарантирует, что transpose_complements будет очищен только если была попытка его создания, что делает код более безопасным и предотвращает неправильные освобождения памяти.

  11. User

    всё равно

  12. Assistant

    Извините за недоразумение. Давайте посмотрим на вашу функцию еще раз и уточним, где именно возникают проблемы с утечками памяти.

    Вы правильно инициализируете transpose_complements и очищаете его в конце работы функции, однако вызов удаления transpose_complements происходит вне зависимости от того, была ли память для него вообще выделена. Важно убедиться, что операция удаления происходит только если s21_adj_matrix была успешно выполнена.

    Также, стоит удостовериться, что вы правильно очищаете память в случае ошибок на любом этапе после успешного создания матрицы result.

    Исправленный код может выглядеть следующим образом:

    int s21_inverse_matrix(matrix_t *A, matrix_t *result) {
      if (A == NULL || A->matrix == NULL || result == NULL) {
        return ERROR_INIT;
      }
      if (A->columns != A->rows) return ERROR_CALC;
    
      int status = s21_create_matrix(A->rows, A->columns, result);
    
      if (status == OK) {
        double det = 0;
        if ((status = s21_determinant(A, &det)) == OK && det != 0) {
          matrix_t transpose_complements = {0};
          if ((status = s21_adj_matrix(A, &transpose_complements)) == OK) {
            status = s21_mult_number(&transpose_complements, 1 / det, result);
            s21_remove_matrix(&transpose_complements);
          }
        }
        if (status != OK) {
          s21_remove_matrix(result); // Только очищаем result, если возникла ошибка после его создания
        }
      }
    
      return status;
    }
    

    Здесь:

    • Матрица transpose_complements инициализируется и удаляется только если s21_adj_matrix был успешно вызван.
    • Матрица result удаляется только в случае ошибок после её успешного создания.
    • Проверки на успешность операций выполняются последовательно, что упрощает понимание логики и помогает избежать проблем с управлением памятью.

    Этот подход должен эффективно предотвратить утечки памяти, связанные с неправильным освобождением ресурсов.

  13. User

    исправь места утечек int s21_adj_matrix(matrix_t *A, matrix_t *result) { if (A == NULL || A->matrix == NULL || result == NULL) { return ERROR_INIT; }

    int status = OK; status = s21_create_matrix(A->rows, A->columns, result);

    if (status == OK) { matrix_t complements_matrix; status = s21_calc_complements(A, &complements_matrix); if (status == OK) { status = s21_transpose(&complements_matrix, result); } s21_remove_matrix(&complements_matrix); } else s21_remove_matrix(result); return status; }

  14. Assistant

    Для исправления потенциальных утечек памяти в функции s21_adj_matrix, необходимо убедиться, что все операции по созданию матриц также учитывают очистку в случае ошибок, которые могут возникнуть дальше в цепочке вызовов функций.

    Также, важно добавить инициализацию переменной complements_matrix перед её использованием, чтобы гарантировать, что вызов s21_remove_matrix(&complements_matrix) будет безопасен даже если s21_calc_complements не был успешно выполнен.

    Исправленная функция может выглядеть следующим образом:

    int s21_adj_matrix(matrix_t *A, matrix_t *result) {
      if (A == NULL || A->matrix == NULL || result == NULL) {
        return ERROR_INIT;
      }
    
      int status = s21_create_matrix(A->rows, A->columns, result);
      if (status == OK) {
        matrix_t complements_matrix = {0};  // Инициализация нулями для безопасности
        status = s21_calc_complements(A, &complements_matrix);
        if (status == OK) {
          status = s21_transpose(&complements_matrix, result);
        }
        s21_remove_matrix(&complements_matrix);  // Безопасно вызывать даже если s21_calc_complements вернул ошибку
      }
      else {
        s21_remove_matrix(result);  // Очистка, если s21_create_matrix не была успешна
      }
      return status;
    }
    

    Здесь:

    • Инициализация complements_matrix нулями гарантирует, что даже если s21_calc_complements не будет выполнен или вернет ошибку, s21_remove_matrix(&complements_matrix) безопасно освободит любые частично выделенные ресурсы, так как начальное состояние matrix будет NULL.
    • Очистка ресурсов result в случае, когда s21_create_matrix завершается с ошибкой, гарантирует, что не будет утечек памяти, связанных с неуспешным созданием result.
    • Эта корректировка обеспечивает правильное и безопасное управление памятью в любом возможном исполнении кода.