Resources | developer.brewmp.com Resources | developer.brewmp.com

Developer

resources

Implementing heap management in an application

Many application developers protect against fragmentation by implementing their own heap managers. The basic approach is to request a large amount of memory from Brew MP during application initialization, then satisfy any later allocation requests from that initial pool. The advantage to this approach is that it allows an application to determine at initialization time whether it has enough memory to run and to guarantee that no other application or system API will take that memory away or fragment it.

Heap managers typically allocate a single large block during initialization and fail if that allocation request cannot be satisfied. This type of implementation is not recommended, as other Brew applications may have fragmented the heap such that no sufficiently large, contiguous block exists.

Instead, the developer should determine the largest contiguous block that the application will actually need, and then implement the heap manager such that it can compose its heap out of multiple sufficiently large blocks. For example, if a total of 12MB is required, the following pseudo-code might be used (this example assumes the heap manager can add additional free nodes after initialization):

#define HEAP_SIZE (12 * 1024 * 1024)
while (pHeapManager->GetFreeSpace() < HEAP_SIZE)
{
  int total, free, largest;
  free = GETRAMFREE(&total, &largest);
  if (largest < (16 * 1024)) 
  { // if we get to this point, we’re too fragmented/low on memory
    break;
  }
  // Calculate how much more we still need
  int size = MIN(largest, HEAP_SIZE - pHeapManager->GetFreeSpace());
  // Allocate and add to the heap manager
  pHeapManager->AddBlock( MALLOC(largest), largest );
}

if (pHeapManager->GetFreeSpace() < HEAP_SIZE)
{
  // Error!!
}

Applicability

While this approach does not improve efficiency in memory utilization, it can be an effective way to ensure that an application can run under predictable conditions. Applications that require large amounts of memory or that perform frequent allocations, such as web browsers and games, should strongly consider this approach.