DIY freeMemory()

I was wondering how much free RAM there was when my programs were running, and I couldn’t find freememory() or freeMemory() (probably not #including the correct header file!) so I decided to write one.

/***************************************************
 * freeMemory() by JD Glover, December 2020
 * Returns biggest allocatable RAM using malloc().
 * Uses binary chop to find it.
 * memunit is the smallest chunk of RAM you want
 * to allocate, in bytes, eg sizeof(double).
 * maxRAM is the total RAM available, again in bytes, 
 * eg 2048 for an Arduino UNO.
 ***************************************************/




unsigned long freeMemory( size_t memunit, unsigned long maxRAM )
{
  unsigned long testblksize;    // block size used to request malloc() for allocation
  unsigned long incblksize;     // incremental increase or decrease of testblksize
  unsigned long maxblksizeisge; // upper limit of maximum block size
  unsigned long maxblksizeislt; // lower limit of maximum block size
  unsigned long smallestinc;    // gotta stop somewhere!
  byte *ptr;                    // pointer returned by malloc()
 
  // setups
  maxblksizeisge = 0;
  maxblksizeislt = maxRAM;
  testblksize = maxRAM;
  incblksize = testblksize / 2;
  smallestinc = memunit;


  while (incblksize >= smallestinc)
  {
    if (testblksize < maxblksizeislt) { testblksize += incblksize; } else { testblksize -= incblksize; }
    ptr = malloc(testblksize);
    if (ptr == NULL) { maxblksizeislt = testblksize; } else { maxblksizeisge = testblksize; free(ptr); }
    incblksize /= 2;
  }
  return maxblksizeislt - smallestinc;
}

It’s quick and dirty, would probably be more efficient with realloc(), but it seems to work. Only been tested on an UNO (that’s all I’ve got to test it on ATM), and has not been stress tested.

Feel free to criticise, test, debug, improve or whatever.