valloc.c 1.7 KB

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