sebbu

test_free_recur

Apr 11th, 2018
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.12 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4.  
  5. struct s1
  6. {
  7.     int a;
  8.     float b;
  9.     char* name;
  10.     struct s2* s2;
  11.     void (*init)(struct s1*);
  12.     void (*free)(struct s1*);
  13. };
  14.  
  15. struct s2
  16. {
  17.     short c;
  18.     double d;
  19.     char* desc;
  20.     struct s1* s1;
  21.     void (*init)(struct s2*);
  22.     void (*free)(struct s2*);
  23. };
  24.  
  25. void s1_free(struct s1* s1)
  26. {
  27.     if(s1==NULL) return;
  28.     printf("s1_free\n");
  29.     s1->a=0;
  30.     s1->b=0.0;
  31.     free(s1->name);
  32.     struct s2* s2=s1->s2;
  33.     s1->s2=NULL;
  34.     s1->init=NULL;
  35.     s1->free=NULL;
  36.     if(s2!=NULL) if(s2->free!=NULL) s2->free(s2);
  37. }
  38.  
  39. void s2_free(struct s2* s2)
  40. {
  41.     if(s2==NULL) return;
  42.     printf("s2_free\n");
  43.     s2->c=0;
  44.     s2->d=0.0;
  45.     free(s2->desc);
  46.     struct s1* s1=s2->s1;
  47.     s2->s1=NULL;
  48.     s2->init=NULL;
  49.     s2->free=NULL;
  50.     if(s1!=NULL) if(s1->free!=NULL) s1->free(s1);
  51. }
  52.  
  53. int main(int argc, char* argv[])
  54. {
  55.     struct s1 s1;
  56.    
  57.     s1.a=5;
  58.     s1.b=3.14;
  59.     s1.name=strdup("coucou");
  60.     s1.free=s1_free;
  61.    
  62.     struct s2 s2;
  63.    
  64.     s2.desc=strdup("Hello World!");
  65.     s2.free=s2_free;
  66.    
  67.     s1.s2=&s2;
  68.     s2.s1=&s1;
  69.    
  70.     if(s1.free!=NULL) s1.free(&s1);
  71.     if(s2.free!=NULL) s2.free(&s2);
  72.     return EXIT_SUCCESS;
  73. }
  74. //
Add Comment
Please, Sign In to add comment