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?
2 Answers
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.
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.
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.
- 7,989
- 2
- 15
- 21
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.
- 105,761
- 5
- 80
- 138

