14. Orangutan System Resources

This section of the library is intended offers general AVR resources. Currently, it only provides information about the amount of free RAM on the AVR.

static unsigned char OrangutanResources::getFreeRAM()

unsigned char get_free_ram()

Returns an estimate of the available free RAM on the AVR, in bytes. This is computed as the difference between the bottom of the stack and the top of the static variable space or the top of the malloc() heap. This function is very useful for avoiding disastrous and diffucult-to-debug problems that can occur at any time due to the nature of the C and C++ programming languages. Local variables and the location of function calls are stored on the stack in RAM, global and data variables take up additional RAM, and some programs dynamically allocate RAM with the malloc() set of functions. While malloc() will refuse to allocate memory that has already been used for another purpose, if the stack grows large enough it will silently overwrite other regions of RAM. This kind of problem, called a stack overflow, can have unexpected and seemingly random effects, such as:

  • a program restart, as if the board was reset,
  • sudden jumps to arbitrary locations in the program,
  • behavior that seems logically impossible, and
  • data corruption.

Small stack overflows that happen rarely might cause bugs that are subtle and hard to detect. We recommend that you use get_free_ram() within your main loop and also at some points within function calls, especially any recursive or highly nested calls, and cause your robot to display an error indicator or a warning of some type if memory gets tight. If your Orangutan is controlling a system that might damage itself or cause danger to an operator it should go into a safe shutdown mode immediately upon detection of a low memory error. For example, a BattleBot could shut down all motors, and a robotic aircraft could deploy its parachute.

By checking available memory at various levels within your code, you can get an idea of how much memory each function call consumes, and think about redesigning the code to use memory more efficiently. The get_free_ram() function itself should not take a noticeable amount of time and use just 6 bytes of RAM itself, so you can use it freely throughout your code.

See the avr-libc malloc page for more information about memory organization in C on the AVR.