I am writing a basic matrix library in c, and the matrix data structure looks like this:
typedef struct Matrix{
int rows;
int cols;
double complex *matrix;
} Matrix;
and the corresponding function to initialize the matrix and the function to free the pointer(similar to constructor and destructor in c++)
Matrix* InitializeMatrix(int r, int c){
Matrix* mat = malloc(sizeof(Matrix));
mat->rows = r;
mat->cols = c;
mat->matrix = (double complex *)malloc(r * c * sizeof(double complex));
return mat;
}
int DeleteMatrix(Matrix *mat){
mat->rows = 0;
mat->cols = 0;
free(mat->matrix);
mat->matrix = 0;
return 0;
}
Here is the main problem. Suppose I have two functions
Matrix* fun1(Matrix* input){
//some operations
Matrix* mat = InitializeMatrix(r, c);
//some operations
return mat;
}
Matrix* fun2(Matrix* input){
//some operations
Matrix* mat = InitializeMatrix(r, c);
//some operations
return mat;
}
Now I have another function want to nest fun1and fun2
Matrix* fun3(Matrix* input){
return fun2(fun1(input));
}
Usually when I call a function, I will have to call DeleteMatrix to free the memory, but in fun2(fun1(input)), the reference to the matrix generated by fun1(input) is not saved, and cannot be freed. I know I can create a intermediate variable to make that reference, but I would like to keep nested function calls since it is neat and intuitive. Is there a problem in my overall design? How to overcome this problem?
Aucun commentaire:
Enregistrer un commentaire