Determining RAM used at a given time

Hi again,

I'd like to periodically assign to a variable the number of bytes of RAM used at that point. In case it matters, I'm using malloc() in a few places. How would I do that?

And as a side question, I'm curious how fragmentation of RAM is dealt with. It's probably more info than my brain will handle though. I suppose problematic fragmentation can be dealt with by avoiding malloc() where possible, and re-using blocks specified at the start?

Thanks

Fragmentation of RAM is not dealt with, either in the Arduino software in particular or in C++ in general. When programming with microcontrollers, it is best to use malloc/calloc/new only in the initialization phase, and not to use free/delete at all.

There are a number of programs available for reporting free memory - a quick Google search will find them.

I'm curious how fragmentation of RAM is dealt with. It's probably more info than my brain will handle though.

It's not dealt with at all, so your brain should be able to handle the process :slight_smile:

Typically in an embedded system you should malloc() only when configuring the program at the start and never again.


Rob

Thanks Rob, DC. Lol @ your comment Rob. I'm not sure if it's better or worse!!

Oddly I managed to get something running which frequently calls malloc() and free(). The code did something like this:

void loop(){
  byte* stuff = malloc(numStuff);
  // do stuff
  free(stuff);

  byte* things = malloc(numThings);
  // do things
  free(things);
}

How is it that bad things didn't happen? I'm using quite a bit of RAM in general. However, "stuff" never used more than about 10 bytes and "things" never used more than about 16 bytes.

Is there any document or explanation somewhere of what exactly malloc() and free() would do on the Arduino?

I think this should explain it - avr-libc: Memory Areas and Using malloc()

Fantastic link, thanks!