fork download
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. typedef struct _Foo_
  5. {
  6. // variables
  7. int number;
  8. char character;
  9.  
  10. // array of float
  11. int arrSize;
  12. float* arr;
  13.  
  14. // pointer to another instance
  15. void* myTwin;
  16. } Foo;
  17.  
  18. Foo* createFoo (int arrSize, Foo* twin);
  19. Foo* destroyFoo (Foo* foo);
  20.  
  21. int main ()
  22. {
  23. Foo* a = createFoo (2, NULL);
  24. Foo* b = createFoo (4, a);
  25.  
  26. destroyFoo(a);
  27. destroyFoo(b);
  28.  
  29. printf("success");
  30. return 0;
  31. }
  32.  
  33. Foo* createFoo (int arrSize, Foo* twin)
  34. {
  35. Foo* t = (Foo*) malloc(sizeof(Foo));
  36.  
  37. // initialize with default values
  38. t->number = 1;
  39. t->character = '1';
  40.  
  41. // initialize the array
  42. t->arrSize = (arrSize>0?arrSize:10);
  43. t->arr = (float*) malloc(sizeof(float) * t->arrSize);
  44.  
  45. // a Foo is a twin with only one other Foo
  46. t->myTwin = twin;
  47. if(twin) twin->myTwin = t;
  48.  
  49. return t;
  50. }
  51.  
  52. Foo* destroyFoo (Foo* foo)
  53. {
  54. if (foo)
  55. {
  56. // we allocated the array, so we have to free it
  57. free(foo->arr);
  58.  
  59. // to avoid broken pointer, we need to nullify the twin pointer
  60. if(foo->myTwin) ((Foo*)foo->myTwin)->myTwin = NULL;
  61. }
  62.  
  63. free(foo);
  64.  
  65. return NULL;
  66. }
  67.  
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
success