Function to calculate the memory available for malloc

Dependents:   AvailableMemory_HelloWorld MCBBThermostat helloaabbc SP14P1_skeleton

Committer:
segundo
Date:
Mon Nov 08 13:21:36 2010 +0000
Revision:
15:d00289c15c89
Parent:
11:0f5d5918761a

        

Who changed what in which revision?

UserRevisionLine numberNew contents of line
segundo 0:a98bf0c96bf1 1 #include "AvailableMemory.h"
segundo 0:a98bf0c96bf1 2 #include <stdlib.h>
segundo 0:a98bf0c96bf1 3
segundo 0:a98bf0c96bf1 4 namespace segundo {
segundo 0:a98bf0c96bf1 5 namespace Utilities {
segundo 0:a98bf0c96bf1 6
segundo 0:a98bf0c96bf1 7 int AvailableMemory(int resolution, int maximum, bool disableInterrupts) {
segundo 0:a98bf0c96bf1 8
segundo 0:a98bf0c96bf1 9 if (resolution < 1) resolution = 1;
segundo 0:a98bf0c96bf1 10 if (maximum < 0) maximum = 0;
segundo 0:a98bf0c96bf1 11
segundo 0:a98bf0c96bf1 12 int low = 0;
segundo 0:a98bf0c96bf1 13 int high = maximum + 1;
segundo 0:a98bf0c96bf1 14
segundo 0:a98bf0c96bf1 15 if (disableInterrupts) __disable_irq();
segundo 0:a98bf0c96bf1 16
segundo 0:a98bf0c96bf1 17 while (high - low > resolution) {
segundo 0:a98bf0c96bf1 18 int mid = (low + high) / 2;
segundo 0:a98bf0c96bf1 19 void* p = malloc(mid);
segundo 0:a98bf0c96bf1 20 if (p == NULL) {
segundo 0:a98bf0c96bf1 21 high = mid;
segundo 0:a98bf0c96bf1 22 } else {
segundo 0:a98bf0c96bf1 23 free(p);
segundo 0:a98bf0c96bf1 24 low = mid;
segundo 0:a98bf0c96bf1 25 }
segundo 0:a98bf0c96bf1 26 }
segundo 0:a98bf0c96bf1 27
segundo 0:a98bf0c96bf1 28 if (disableInterrupts) __enable_irq();
segundo 0:a98bf0c96bf1 29
segundo 0:a98bf0c96bf1 30 return low;
segundo 0:a98bf0c96bf1 31 }
segundo 0:a98bf0c96bf1 32
segundo 0:a98bf0c96bf1 33 } // namespace Utilities
segundo 0:a98bf0c96bf1 34 } // namespace segundo