Home > Net >  Is returning pointer to struct-pointer created inside a function safe?
Is returning pointer to struct-pointer created inside a function safe?

Time:10-11

Is it a safe practice to do this? Will the local variable mat get destroyed after the multiply() function is complete? Will this effect mat4 later in the main() program?

In matrix.h

typedef struct Matrix
{
    double **entries;
    int rows;
    int cols;
} Matrix;

In matrix.c

int check_dimensions_for_multiplication(Matrix *m1, Matrix *m2)
{
    if (m1->cols == m2->rows)
        return 1;
    return 0;
}

Matrix *matrix_create(int rows, int cols)
{
    Matrix *matrix = malloc(sizeof(Matrix));
    matrix->rows = rows;
    matrix->cols = cols;
    matrix->entries = malloc(rows * sizeof(double *));
    for (int i = 0; i < rows; i  )
    {
        matrix->entries[i] = malloc(cols * sizeof(double));
    }
    return matrix;
}

Matrix *multiply(Matrix *m1, Matrix *m2)
{
    if (check_dimensions_for_multiplication(m1, m2))
    {
        Matrix *mat = matrix_create(m1->rows, m2->cols);
        for (int i = 0; i < m1->rows; i  )
        {
            for (int j = 0; j < m2->cols; j  )
            {
                mat->entries[i][j] = m1->entries[i][j] * m2->entries[i][j];
            }
        }
        return mat;
    }
    else
    {
        printf("Dimension mismatch multiply: %dx%d %dx%d\n", m1->rows, m1->cols, m2->rows, m2->cols);
        exit(1);
    }
}

In main.c:

Matrix *mat4 = multiply(mat2, mat1);

CodePudding user response:

No, variables allocated in the heap via malloc should not be destroyed after the function terminates.

int * someInteger = malloc(sizeof(int));

This code will allocate some memory (probably 4 bytes) at a location called the heap, a space given to your program by the Operating System. Memory allocated in the Heap is a permanent piece of memory that propagates throughout the lifetime of your program unless you free that particular pointer.

Only assigned local variables are destroyed since they are stored on the stack.

You can check this website if you want more information on local variables and stack

http://users.cecs.anu.edu.au/~Matthew.James/engn3213-2002/notes/upnode25.html#:~:text=The stack is used for,variables in the stack frame.

  • Related