fork download
  1. #include <stdio.h>
  2. #include <stdlib.h> // malloc, free
  3.  
  4. // Define GSL matrix type for testing purposes
  5. typedef struct gsl_matrix {
  6. int rows;
  7. int cols;
  8. double **data;
  9. } gsl_matrix;
  10.  
  11. // Define gsl_matrix_free function for testing purposes
  12. void gsl_matrix_free(gsl_matrix *m) {
  13. for (int i = 0; i < m->rows; i++) {
  14. free(m->data[i]);
  15. }
  16. free(m->data);
  17. free(m);
  18. }
  19.  
  20. #define Fn_apply(type, fn, ...) \
  21.   { \
  22.   void *stopper_for_apply = (int[]){0}; \
  23.   type **list_for_apply = (type*[]){__VA_ARGS__, stopper_for_apply}; \
  24.   for (int i = 0; list_for_apply[i] != stopper_for_apply; i++) \
  25.   fn(list_for_apply[i]); \
  26.   }
  27.  
  28. #define Free_all(...) Fn_apply(void, free, __VA_ARGS__)
  29.  
  30. #define Gsl_vector_free_all(...) \
  31.   Fn_apply(gsl_vector, gsl_vector_free, __VA_ARGS__)
  32.  
  33. #define Gsl_matrix_free_all(...) \
  34.   Fn_apply(gsl_matrix, gsl_matrix_free, __VA_ARGS__)
  35.  
  36. int main() {
  37. // Allocate memory for test pointers
  38. double *x = malloc(10 * sizeof(double));
  39. double *y = malloc(100 * sizeof(double));
  40. double *z = malloc(1000 * sizeof(double));
  41.  
  42. // Free memory using the Free_all macro
  43. Free_all(x, y, z);
  44.  
  45. // Allocate memory for test GSL matrices
  46. gsl_matrix *m1 = malloc(sizeof(gsl_matrix));
  47. m1->rows = 3;
  48. m1->cols = 3;
  49. m1->data = malloc(m1->rows * sizeof(double *));
  50. for (int i = 0; i < m1->rows; i++) {
  51. m1->data[i] = malloc(m1->cols * sizeof(double));
  52. }
  53.  
  54. gsl_matrix *m2 = malloc(sizeof(gsl_matrix));
  55. m2->rows = 2;
  56. m2->cols = 2;
  57. m2->data = malloc(m2->rows * sizeof(double *));
  58. for (int i = 0; i < m2->rows; i++) {
  59. m2->data[i] = malloc(m2->cols * sizeof(double));
  60. }
  61.  
  62. // Free GSL matrices using the Gsl_matrix_free_all macro
  63. Gsl_matrix_free_all(m1, m2);
  64.  
  65. return 0;
  66. }
  67.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Standard output is empty