m1cky22
m1cky22

Reputation: 208

Freeing returned variable in C

Say I have the following setup:

struct matrix
{
    int row, col;
};

struct matrix* createMatrix(int row, int col)
{
    struct matrix* t_matrix;
    t_matrix = (struct matrix*) malloc(sizeof(struct matrix));
    t_matrix->row = row;
    t_matrix->col = col;

    return t_matrix;
}

and then I want to have a function that temporarily returns a struct matrix*, but does not change the original matrix (very important):

struct matrix* transpose(struct matrix* mat)
{
    return createMatrix(mat->col, mat->row);
}

How do I now free this transposed matrix, but still use its value temporarily?

EDIT: removed unnecessary parameter of createMatrix

SOLVED: As some suggested, I ended up making a pointer to all my matrices and freeing them upon ending the program.

Upvotes: 2

Views: 212

Answers (2)

R Sahu
R Sahu

Reputation: 206567

The key point to remember is there needs to be a free for every malloc. Here's some example code that illustrates how you could use the functions.

// Create a matrix
struct matrix* m1 = createMatrix(10, 15);

// Create a transpose of the matrix.
struct matrix* mt1 = transpose(m1)

// Create another transpose of the matrix.
struct matrix* mt2 = transpose(m1)

// Free the second transposed matrix
free(mt2);

// Free the first transposed matrix
free(mt1);

// Free the original matrix
free(m1);

Upvotes: 0

SylvainL
SylvainL

Reputation: 3938

Usually, you tell in the documentation of the function that it returns a new object matrix (ie, it doesn't change any matrix passed as an argument) and that it is the responsability of the calling code to free it when it's no longer in use.

Another possibility would be to store somewhere the list of these newly created matrix and dispose or reuse them when by some criteria, you know that they are no longer in use; for example by using a flag, a time stamp, etc.

Upvotes: 1

Related Questions