fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void* AllocateLargestFreeBlock(size_t* Size)
  5. {
  6. size_t s0, s1;
  7. void* p;
  8.  
  9. s0 = ~(size_t)0 ^ (~(size_t)0 >> 1);
  10.  
  11. while (s0 && (p = malloc(s0)) == NULL)
  12. s0 >>= 1;
  13.  
  14. if (p)
  15. free(p);
  16.  
  17. s1 = s0 >> 1;
  18.  
  19. while (s1)
  20. {
  21. if ((p = malloc(s0 + s1)) != NULL)
  22. {
  23. s0 += s1;
  24. free(p);
  25. }
  26. s1 >>= 1;
  27. }
  28.  
  29. while (s0 && (p = malloc(s0)) == NULL)
  30. s0 ^= s0 & -s0;
  31.  
  32. *Size = s0;
  33. return p;
  34. }
  35.  
  36. size_t GetFreeSize(void)
  37. {
  38. size_t total = 0;
  39. void* pFirst = NULL;
  40. void* pLast = NULL;
  41.  
  42. for (;;)
  43. {
  44. size_t largest;
  45. void* p = AllocateLargestFreeBlock(&largest);
  46.  
  47. if (largest < sizeof(void*))
  48. {
  49. if (p != NULL)
  50. free(p);
  51. break;
  52. }
  53.  
  54. *(void**)p = NULL;
  55.  
  56. total += largest;
  57.  
  58. if (pFirst == NULL)
  59. pFirst = p;
  60.  
  61. if (pLast != NULL)
  62. *(void**)pLast = p;
  63.  
  64. pLast = p;
  65. }
  66.  
  67. while (pFirst != NULL)
  68. {
  69. void* p = *(void**)pFirst;
  70. free(pFirst);
  71. pFirst = p;
  72. }
  73.  
  74. return total;
  75. }
  76.  
  77. int main(void)
  78. {
  79. printf("Total free: %zu\n", GetFreeSize());
  80. printf("Total free: %zu\n", GetFreeSize());
  81. printf("Total free: %zu\n", GetFreeSize());
  82. printf("Total free: %zu\n", GetFreeSize());
  83. printf("Total free: %zu\n", GetFreeSize());
  84. return 0;
  85. }
  86.  
Success #stdin #stdout 0.02s 2744KB
stdin
Standard input is empty
stdout
Total free: 266677120
Total free: 266673024
Total free: 266673024
Total free: 266673024
Total free: 266673024