3

I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?

4

I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?

The first thing that happens is that malloc() will return NULL saying that memory could not be allocated. The AVR heap implementation has a few safety measures. One is to check that there is a minimum margin (__malloc_margin) between end of the heap and the top of the stack. This can be adjusted by the application.

Heap-Stack

Typically the minimum margin should be able to hold the largest stack usage (typically deepest function call tree with the largest local variables usage) plus largest ISR stack usage.

If the stack runs into the heap the memory block/s at the end of the heap is/are corrupted. What happens depends on the type of data structure.

Not checking NULL return from malloc() gives some interesting errors on the AVR as the processors registers are memory mapped. NULL points to R0.

AVR Memory Map

A good rule of thumb when using malloc() in small scale embedded systems is 1) avoid it, 2) allocate memory with malloc() during the setup(). All other dynamic memory need be allocated temporary on stack and only for the processing.

  • allocate memory with malloc() during the setup()”. If you know from the very beginning how much memory you need, there is no point in using malloc() instead of static buffers. As to what usages of malloc() are safe, see my answer to a related question. – Edgar Bonet Feb 1 '16 at 14:30
  • 1
    @EdgarBonet I seem to have missed one of the requirements; software with dynamic configuration, e.g. EEPROM variables that say number of elements, etc. The actual size of the dynamic data structure is not known at compile time or is allowed to change. In other cases, I fully agree with your objection. If the size is known avoid malloc(). – Mikael Patel Feb 1 '16 at 14:45
2

In simple terms: if the stack and heap have collided then the program will most likely crash, and any countermeasures you may have in place are now null and void.

However, you can find out the current amount of free memory quite easily by looking at where the top of the heap is and creating a local variable on the stack and getting its address - subtract one from the other and you get the free memory size.

That's exactly what the MemoryFree Library does for you.

  • What happens if the program crashes? Will the AVR reset the program? – Ahmad Naoum Dec 31 '15 at 20:30
  • Anything at all can happen. No one can predict what might happen. The watchdog exists as a method to try and recover from such scenarios. – Majenko Dec 31 '15 at 20:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.