valloc.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. #define MALLOC_HEADER_SIZE 12
  9. static int count = 0;
  10. static int use = 0;
  11. void *v_malloc(size_t size)
  12. {
  13. if (size == 0) { return NULL; }
  14. void *p = malloc(size + HEADER_SIZE);
  15. if (!p) { return NULL; }
  16. *(int *)p = (int)size;
  17. count++;
  18. use += (int)size + MALLOC_HEADER_SIZE;
  19. return (char *)p + HEADER_SIZE;
  20. }
  21. void *v_calloc(size_t num, size_t size)
  22. {
  23. size_t total = num * size;
  24. void *p = v_malloc(total);
  25. if (p) { memset(p, 0, total); }
  26. return p;
  27. }
  28. void v_free(void *block)
  29. {
  30. if (!block) { return; }
  31. void *p = (char *)block - HEADER_SIZE;
  32. int size = *(int *)p;
  33. count--;
  34. use -= size + MALLOC_HEADER_SIZE;
  35. free(p);
  36. }
  37. void *v_realloc(void *block, size_t size)
  38. {
  39. if (size == 0)
  40. {
  41. v_free(block);
  42. return NULL;
  43. }
  44. int old_size = 0;
  45. void *raw = NULL;
  46. if (block)
  47. {
  48. raw = (char *)block - HEADER_SIZE;
  49. old_size = *(int *)raw;
  50. }
  51. void *p = realloc(raw, size + HEADER_SIZE);
  52. if (!p) { return NULL; }
  53. *(int *)p = (int)size;
  54. if (!block) { count++; }
  55. use += (int)(size - old_size);
  56. return (char *)p + HEADER_SIZE;
  57. }
  58. int v_mcheck(int *dstCount, int *dstUse)
  59. {
  60. if (dstCount) { *dstCount = count; }
  61. if (dstUse) { *dstUse = use; }
  62. return 0;
  63. }
  64. int32_t vallocGetArea(void)
  65. {
  66. int32_t area2 = 0, use2 = 0;
  67. v_mcheck(&area2, &use2);
  68. return area2;
  69. }
  70. int32_t vallocGetUse(void)
  71. {
  72. int32_t area2 = 0, use2 = 0;
  73. v_mcheck(&area2, &use2);
  74. return use2;
  75. }
  76. void displayMem(void)
  77. {
  78. int32_t area2 = 0, use2 = 0;
  79. v_mcheck(&area2, &use2);
  80. printf("|||----------->>> area = %d, size = %d\r\n", area2, use2);
  81. }