Split a memory unit in two units. One of size "size" and the second with left over space. The second unit is put into the free memory units
| 76 | /// Split a memory unit in two units. One of size "size" and the second with |
| 77 | /// left over space. The second unit is put into the free memory units |
| 78 | void HeapAllocator::splitMemoryUnit(MemoryUnitHeader* unit, size_t size) { |
| 79 | |
| 80 | assert(!unit->isAllocated); |
| 81 | |
| 82 | // If the size of the unit is large enough to be slit |
| 83 | if (size + sizeof(MemoryUnitHeader) < unit->size) { |
| 84 | |
| 85 | // Create a new memory unit with left over space |
| 86 | unsigned char* newUnitLocation = (reinterpret_cast<unsigned char*>(unit)) + sizeof(MemoryUnitHeader) + size; |
| 87 | MemoryUnitHeader* newUnit = new (static_cast<void*>(newUnitLocation)) MemoryUnitHeader(unit->size - sizeof(MemoryUnitHeader) - size, unit, unit->nextUnit, unit, unit->nextFreeUnit, unit->isNextContiguousMemory); |
| 88 | assert(newUnit->nextUnit != newUnit); |
| 89 | unit->nextUnit = newUnit; |
| 90 | unit->nextFreeUnit = newUnit; |
| 91 | if (newUnit->nextUnit != nullptr) { |
| 92 | newUnit->nextUnit->previousUnit = newUnit; |
| 93 | } |
| 94 | if (newUnit->nextFreeUnit != nullptr) { |
| 95 | newUnit->nextFreeUnit->previousFreeUnit = newUnit; |
| 96 | } |
| 97 | |
| 98 | assert(unit->nextUnit != unit); |
| 99 | unit->isNextContiguousMemory = true; |
| 100 | unit->size = size; |
| 101 | |
| 102 | assert(unit->previousUnit == nullptr || unit->previousUnit->nextUnit == unit); |
| 103 | assert(unit->nextUnit == nullptr || unit->nextUnit->previousUnit == unit); |
| 104 | |
| 105 | assert(unit->previousFreeUnit == nullptr || unit->previousFreeUnit->nextFreeUnit == unit); |
| 106 | assert(unit->nextFreeUnit == nullptr || unit->nextFreeUnit->previousFreeUnit == unit); |
| 107 | |
| 108 | assert(newUnit->previousUnit == nullptr || newUnit->previousUnit->nextUnit == newUnit); |
| 109 | assert(newUnit->nextUnit == nullptr || newUnit->nextUnit->previousUnit == newUnit); |
| 110 | |
| 111 | assert(newUnit->previousFreeUnit->nextFreeUnit == newUnit); |
| 112 | assert(newUnit->nextFreeUnit == nullptr || newUnit->nextFreeUnit->previousFreeUnit == newUnit); |
| 113 | |
| 114 | assert(unit->nextFreeUnit == newUnit); |
| 115 | assert(newUnit->previousFreeUnit == unit); |
| 116 | assert(!newUnit->isAllocated); |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | // Allocate memory of a given size (in bytes) and return a pointer to the |
| 121 | // allocated memory. |
nothing calls this directly
no outgoing calls
no test coverage detected