Classic Nano has too much RAM

I was running a sketch where I needed to check the amount of available memory after certain operations/function calls. To my surprise, I got strange results.

The below (trimmed down) sketch reported more memory than the Nano actually has. The freeMemory() function was taken from Measuring Memory Usage | Memories of an Arduino | Adafruit Learning System

Sketch

void setup()
{
  Serial.begin(115200);
  Serial.println(F("String (capital S) memory test"));

  Serial.print(F("Free RAM = "));
  Serial.println(freeMemory());
}

void loop()
{
}

#ifdef __arm__
// should use uinstd.h to define sbrk but Due causes a conflict
extern "C" char* sbrk(int incr);
#else   // __ARM__
extern char *__brkval;
#endif  // __arm__

#ifdef __arm__
// should use uinstd.h to define sbrk but Due causes a conflict
extern "C" char* sbrk(int incr);
#else   // __ARM__
extern char *__brkval;
#endif  // __arm__

int freeMemory()
{
  char top;
#ifdef __arm__
  return &top - reinterpret_cast<char*>(sbrk(0));
#elif defined(CORE_TEENSY) || (ARDUINO > 103 && ARDUINO != 151)
  return &top - __brkval;
#else   // __arm__
  return __brkval ? &top - __brkval : &top - __malloc_heap_start;
#endif  // __arm__
}

Output

String (capital S) memory test
Free RAM = 2299

Anybody any idea?

All of the arm and ARM references make me think that this version of freeMemory() was intended for ARM processors, not the AVR processor on the classic Nano.

Remove these two lines and try again:

I think @pylon may be on to something...

#elif defined(CORE_TEENSY) || (ARDUINO > 103 && ARDUINO != 151)

If @sterretje is using, for example, IDE 1.8, then the above will give the result

return &top - __brkval;

but what if __brkval is zero? That possibility is not checked, but in the other version

return __brkval ? &top - __brkval : &top - __malloc_heap_start;

it does check if __brkval is zero, and uses __malloc_heap_start instead in that case.

So maybe that line that is being used is incorrect, a bug, because it does not check for __brkval being zero.

If RAM begins at, say, address 256 then &top could be around 256+2048 = 2304 less a few bytes = 2299?

Thanks people for the replies

A more sensible 1845 bytes free :+1:

If I ever feel the need to dig deeper, ...

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.