Advertisement
Guest User

Untitled

a guest
May 24th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. char* pool_new(Pool& pool, int size)
  2. {
  3.     char *ptr = pool.buffer;
  4.  
  5.     int size_counter = 0; // Blocks amount
  6.     while (size_counter + size < pool.size) { // Execute while we are below the memory limit.
  7.         int block_size = *reinterpret_cast<int*>(ptr); // Non-free block size
  8.  
  9.         if (block_size > 0) {
  10.             ptr += block_size;
  11.             size_counter += block_size; // Increase size_counter until we reach a "free" block
  12.             continue;
  13.         } else if (block_size < 0) { // When we reach a "free" block
  14.             if (size + sizeof(int) <= -block_size) {
  15.                 *reinterpret_cast<int*>(ptr) = size + sizeof(int);
  16.                 *reinterpret_cast<int*>(ptr + size + sizeof(int)) = block_size + size + sizeof(int);
  17.                 return ptr + sizeof(int);
  18.             } else {
  19.                 size_counter += (-block_size);
  20.                 ptr += block_size;
  21.                 continue;
  22.             }
  23.         } else {
  24.             return nullptr;
  25.         }
  26.     }
  27.  
  28.     return nullptr;
  29. }
  30.  
  31. void pool_delete(char* at)
  32. {
  33.     at -= sizeof(int);
  34.     int size = *reinterpret_cast<int*>(at);
  35.     *reinterpret_cast<int*>(at) = -size;
  36.     for (int i = sizeof(int); i < size; i++) at[i] = 0;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement