This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Malloc Test

By: a guest on Jul 23rd, 2013  |  syntax: C  |  size: 1.11 KB  |  views: 40  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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. }
clone this paste RAW Paste Data