Advertisement
Guest User

Malloc Test

a guest
Jul 23rd, 2013
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | None | 0 0
  1. #include <stddef.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. #ifndef TEST_SIZE
  6.     #define TEST_SIZE 16
  7. #endif
  8.  
  9. char* arenas[20];
  10. size_t numArenas;
  11.  
  12. size_t newArenaGap = 8192;
  13.  
  14. size_t nearestArena(char* ptr)
  15. {
  16.     size_t bestGap = newArenaGap;
  17.     size_t best;
  18.     for (int i = 0; i < numArenas; ++i) {
  19.         size_t gap = labs(ptr-arenas[i]);
  20.         if (gap < bestGap) {
  21.             best = i;
  22.             bestGap = gap;
  23.         }
  24.     }
  25.     if (bestGap < newArenaGap)
  26.         return best;
  27.     arenas[numArenas] = ptr;
  28.     return numArenas++;
  29. }
  30.  
  31. void doMalloc(size_t size) {
  32.     char* mem = (char*) malloc(size);
  33.     if (newArenaGap < size*2)
  34.         newArenaGap = size*2;
  35.     size_t i = nearestArena(mem);
  36.     if (arenas[i] != mem) {
  37.         ptrdiff_t delta = (char*)mem - (char*)arenas[i];
  38.         printf("malloc(%zu)\t= %p (%c%+zd)\n", size, mem, 'p'+i, delta);
  39.     } else {
  40.         printf("malloc(%zu)\t= %p (%c)\n", size, mem,'p'+i);
  41.     }
  42. }
  43.  
  44. int main()
  45. {
  46.     for(int i = 0; i < 16; ++i) {
  47.         doMalloc(TEST_SIZE);
  48.         doMalloc(TEST_SIZE*(2<<i));
  49.     }
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement