Text::Markdown::Discount
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.0 KiB

  1. /*
  2. * debugging malloc()/realloc()/calloc()/free() that attempts
  3. * to keep track of just what's been allocated today.
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #define MAGIC 0x1f2e3d4c
  8. struct alist { int magic, size; struct alist *next, *last; };
  9. static struct alist list = { 0, 0, 0, 0 };
  10. static int mallocs=0;
  11. static int reallocs=0;
  12. static int frees=0;
  13. void *
  14. acalloc(int size, int count)
  15. {
  16. struct alist *ret = calloc(size + sizeof(struct alist), count);
  17. if ( ret ) {
  18. ret->magic = MAGIC;
  19. ret->size = size * count;
  20. if ( list.next ) {
  21. ret->next = list.next;
  22. ret->last = &list;
  23. ret->next->last = ret;
  24. list.next = ret;
  25. }
  26. else {
  27. ret->last = ret->next = &list;
  28. list.next = list.last = ret;
  29. }
  30. ++mallocs;
  31. return ret+1;
  32. }
  33. return 0;
  34. }
  35. void*
  36. amalloc(int size)
  37. {
  38. return acalloc(size,1);
  39. }
  40. void
  41. afree(void *ptr)
  42. {
  43. struct alist *p2 = ((struct alist*)ptr)-1;
  44. if ( p2->magic == MAGIC ) {
  45. p2->last->next = p2->next;
  46. p2->next->last = p2->last;
  47. ++frees;
  48. free(p2);
  49. }
  50. else
  51. free(ptr);
  52. }
  53. void *
  54. arealloc(void *ptr, int size)
  55. {
  56. struct alist *p2 = ((struct alist*)ptr)-1;
  57. struct alist save;
  58. if ( p2->magic == MAGIC ) {
  59. save.next = p2->next;
  60. save.last = p2->last;
  61. p2 = realloc(p2, sizeof(*p2) + size);
  62. if ( p2 ) {
  63. p2->size = size;
  64. p2->next->last = p2;
  65. p2->last->next = p2;
  66. ++reallocs;
  67. return p2+1;
  68. }
  69. else {
  70. save.next->last = save.last;
  71. save.last->next = save.next;
  72. return 0;
  73. }
  74. }
  75. return realloc(ptr, size);
  76. }
  77. void
  78. adump()
  79. {
  80. struct alist *p;
  81. for ( p = list.next; p && (p != &list); p = p->next ) {
  82. fprintf(stderr, "allocated: %d byte%s\n", p->size, (p->size==1) ? "" : "s");
  83. fprintf(stderr, " [%.*s]\n", p->size, (char*)(p+1));
  84. }
  85. if ( getenv("AMALLOC_STATISTICS") ) {
  86. fprintf(stderr, "%d malloc%s\n", mallocs, (mallocs==1)?"":"s");
  87. fprintf(stderr, "%d realloc%s\n", reallocs, (reallocs==1)?"":"s");
  88. fprintf(stderr, "%d free%s\n", frees, (frees==1)?"":"s");
  89. }
  90. }