valloc.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <pthread.h>
  5. #include <unistd.h>
  6. #include "valloc.h"
  7. #define HEADER_SIZE sizeof(int)
  8. static pthread_mutex_t mutex;
  9. static int count = 0;
  10. static int use = 0;
  11. void *v_malloc(size_t size)
  12. {
  13. if (size == 0)
  14. {
  15. return NULL;
  16. }
  17. void *p = malloc(size + HEADER_SIZE);
  18. if (!p)
  19. {
  20. return NULL;
  21. }
  22. *(int *)p = (int)size;
  23. pthread_mutex_lock(&mutex);
  24. count++;
  25. use += (int)size;
  26. pthread_mutex_unlock(&mutex);
  27. return (char *)p + HEADER_SIZE;
  28. }
  29. void *v_calloc(size_t num, size_t size)
  30. {
  31. size_t total = num * size;
  32. void *p = v_malloc(total);
  33. if (p)
  34. {
  35. memset(p, 0, total);
  36. }
  37. return p;
  38. }
  39. void v_free(void *block)
  40. {
  41. if (!block)
  42. {
  43. return;
  44. }
  45. void *p = (char *)block - HEADER_SIZE;
  46. int size = *(int *)p;
  47. pthread_mutex_lock(&mutex);
  48. count--;
  49. use -= size;
  50. pthread_mutex_unlock(&mutex);
  51. free(p);
  52. }
  53. void *v_realloc(void *block, size_t size)
  54. {
  55. if (size == 0)
  56. {
  57. v_free(block);
  58. return NULL;
  59. }
  60. int old_size = 0;
  61. void *raw = NULL;
  62. if (block)
  63. {
  64. raw = (char *)block - HEADER_SIZE;
  65. old_size = *(int *)raw;
  66. }
  67. void *p = realloc(raw, size + HEADER_SIZE);
  68. if (!p)
  69. {
  70. return NULL;
  71. }
  72. *(int *)p = (int)size;
  73. pthread_mutex_lock(&mutex);
  74. if (!block)
  75. {
  76. count++;
  77. }
  78. use += (int)(size - old_size);
  79. pthread_mutex_unlock(&mutex);
  80. return (char *)p + HEADER_SIZE;
  81. }
  82. int v_mcheck(int *dstCount, int *dstUse)
  83. {
  84. pthread_mutex_lock(&mutex);
  85. if (dstCount)
  86. {
  87. *dstCount = count;
  88. }
  89. if (dstUse)
  90. {
  91. *dstUse = use;
  92. }
  93. pthread_mutex_unlock(&mutex);
  94. return 0;
  95. }
  96. void displayMem(void)
  97. {
  98. int32_t area2 = 0, use2 = 0;
  99. v_mcheck(&area2, &use2);
  100. printf("|||----------->>> area = %d, size = %d\r\n", area2, use2);
  101. }
  102. void vallocInit(void)
  103. {
  104. pthread_mutex_init(&mutex, NULL);
  105. }