fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <errno.h>
  4.  
  5. typedef struct my_struct {
  6. int *x;
  7. float *y;
  8. long int *z;
  9. } my_struct;
  10.  
  11. void destroy(my_struct *s);
  12.  
  13. int init(my_struct **ms)
  14. {
  15. my_struct *s = NULL;
  16. do{
  17. s= (my_struct *) malloc(sizeof(my_struct));
  18. if (s == NULL) {
  19. printf("alloc my_struct fail\n");
  20. break;
  21. }
  22.  
  23. s->x = (int *) malloc(sizeof(int));
  24. if (s->x == NULL) {
  25. printf("alloc x fail\n");
  26. break;
  27. }
  28.  
  29. s->y = (float *) malloc(sizeof(float));
  30. if (s->y == NULL) {
  31. printf("alloc y fail\n");
  32. break;
  33. }
  34.  
  35. s->z = (long int*) malloc(sizeof(long int));
  36. if (s->z == NULL) {
  37. printf("alloc z fail\n");
  38. break;
  39. }
  40. *ms = s;
  41. return 0;// success init
  42. }while(0);
  43.  
  44.  
  45. //something wrong
  46. destroy(s);
  47. *ms = NULL;
  48. return -ENOMEM;
  49.  
  50. }
  51.  
  52. void destroy(my_struct *s)
  53. {
  54. if(s == NULL){
  55. return;
  56. }
  57.  
  58. if (s->x != NULL) {
  59. free(s->x);
  60. }
  61.  
  62. if (s->y != NULL) {
  63. free(s->y);
  64. }
  65.  
  66. if (s->z != NULL) {
  67. free(s->z);
  68. }
  69.  
  70. free(s);
  71. }
  72.  
  73. int main(int argc, const char *argv[])
  74. {
  75. my_struct *s = NULL;
  76. if (init(&s)) {
  77. printf("Init my_struct failed\n");
  78. return -ENOMEM;
  79. }
  80.  
  81. // use my_struct here ...
  82.  
  83. destroy(s);
  84.  
  85. return 0;
  86. }
Success #stdin #stdout 0s 2180KB
stdin
Standard input is empty
stdout
Standard output is empty