fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <signal.h>
  4.  
  5. int index = 0;
  6. int max_size = 5;
  7. void **mem = NULL;
  8.  
  9. void *newmem(size_t size) {
  10. void *temp = malloc(size), **temp2;
  11. int i;
  12. if (temp == NULL) {
  13. exit(EXIT_FAILURE);
  14. }
  15. if (mem == NULL) {
  16. mem = (void**)malloc(max_size * sizeof(void*));
  17. if (mem == NULL) {
  18. exit(EXIT_FAILURE);
  19. }
  20. }
  21. mem[index++] = temp;
  22. if (index >= max_size) {
  23. temp2 = (void**)realloc(mem, (max_size + 5) * sizeof(void*));
  24. if (temp2 == NULL) {
  25. exit(EXIT_FAILURE);
  26. }
  27. mem = temp2;
  28. max_size += 5;
  29. }
  30. puts("alloc!");
  31. return temp;
  32. }
  33.  
  34. void releasemem(void) {
  35. int i;
  36. if (mem == NULL) {
  37. return;
  38. }
  39. for (i = 0; i < index; i++) {
  40. if (mem[i] != NULL) {
  41. printf("%d ", *(int*)mem[i]);
  42. free(mem[i]);
  43. mem[i] = NULL;
  44. puts("free!");
  45. }
  46. }
  47. free(mem);
  48. index = 0;
  49. mem = NULL;
  50. }
  51.  
  52. void foo() {
  53. puts("abort");
  54. abort();
  55. }
  56.  
  57. void bar() {
  58. puts("exit failure");
  59. exit(EXIT_FAILURE);
  60. }
  61.  
  62. void baz() {
  63. puts("exit success");
  64. exit(EXIT_SUCCESS);
  65. }
  66.  
  67.  
  68. int main(void) {
  69. int i, *p;
  70.  
  71. atexit(releasemem);
  72. signal(SIGABRT, releasemem);
  73.  
  74. for (i = 0; i < 15; i++) {
  75. p = (int*)newmem(sizeof(int));
  76. *p = i;
  77. }
  78.  
  79. i = getchar();
  80. if (i == '1') {
  81. foo();
  82. } else if (i == '2') {
  83. bar();
  84. } else if (i == '3') {
  85. baz();
  86. }
  87.  
  88. puts("finish");
  89. return 0;
  90. }
  91.  
Runtime error #stdin #stdout 0s 2188KB
stdin
1
stdout
alloc!
alloc!
alloc!
alloc!
alloc!
alloc!
alloc!
alloc!
alloc!
alloc!
alloc!
alloc!
alloc!
alloc!
alloc!
abort
0 free!
1 free!
2 free!
3 free!
4 free!
5 free!
6 free!
7 free!
8 free!
9 free!
10 free!
11 free!
12 free!
13 free!
14 free!