Don't understand how my code runs out of dynamic memory

I've got a fairly complex program, which is spread across several files. I only need an array (280 bytes) and a character buffer (64) bytes, but when I compile it says that I'm close to the limit of dynamic memory. By commenting out some function calls the dynamic memory usage goes down, which suggests to me that the compiler is allocating dynamic memory in addition to my requirement. How can determine what is really being used?

It will only allocate dynamic memory based on your requirements. So I think there must be other memory your code needs in addition to your array and character buffer.

One thing you may not realise is that every string your code is printing takes up dynamic memory.

Serial.println("123456790");

for example will take 11 bytes of dynamic memory.

You can avoid this using the F() macro:

Serial.println(F("123456790"));

which stores the string only in flash memory, not also in dynamic memory.

When you use any of the built-in functions or libraries, they may use up some ram. For example, if you use Serial, you'll probably have both a transmit and a receive buffer, 32 bytes each as I remember. But I don't know how to find out how much ram is allocated to each function.

Also, in IDE v1.8.x, it appears to warn you when you reach 75% ram usage. But I think that's just a rule of thumb. It doesn't necessarily mean it won't run just fine.

If your array is static data that won't change, then it too can be stored in flash memory using PROGMEM.

You may be fine if you don't use any libraries that do run time storage allocation. Things like SD card, graphic displays and neopixels (to name a few common ones) do run time allocation which can run out of ram.

OK, thanks. I had assumed that declaring something as const put it into flash, but clearly it doesn't for the Nano. I've come up with a way to eliminate a constant table which took up quite a lot of memory, and now the compiler reports usage down to around 30%, which is much healthier. I was seeing messages being sent over the USB being corrupted which I guess was a result of stack overflowing.

Many thanks!