Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);

>Solution :

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%20stack%20is%20used%20for,variables%20in%20the%20stack%20frame.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading