I have encountered a problem in a C program running on an AVR microcontroller (ATMega328P). I believe it is due to a stack/heap collision but I'd like to be able to confirm this.
Is there any way I can visualise SRAM usage by the stack and the heap?
Note: the program is compiled with avr-gcc and uses avr-libc.
Update: The actual problem I am having is that the malloc implementation is failing (returning NULL
). All malloc
ing happens on startup and all free
ing happens at the end of the application (which in practice is never since the main part of the application is in an infinite loop). So I'm sure fragmentation is not the issue.
You say malloc is failing and returning NULL:
The obvious cause which you should look at first is that your heap is "full" - i.e, the memory you've asked to malloc cannot be allocated, because it's not available.
There are two scenarios to bear in mind:
a: You have a 16 K heap, you've already malloced 10 K and you try and malloc a further 10K. Your heap is simply too small.
b: More commonly, you have a 16 k Heap, you've been doing a bunch of malloc/free/realloc calls and your heap is less than 50% 'full': You call malloc for 1K and it FAILS - what's up? Answer - the heap free space is fragmented - there isn't a contigous 1K of free memory that can be returned. C Heap managers can not compact the heap when this happens, so you're generally in a bad way. There are techniques to avoid fragmentation, but it's difficult to know if this is really the problem. You'd need to add logging shims to malloc and free so that you can get an idea of what dynamic memory operations are being performed.
EDIT:
You say all mallocs happen at startup, so fragmentation isn't the issue.
In which case, it should be easy to replace the dynamic allocation with static.
old code example:
char *buffer;
void init()
{
buffer = malloc(BUFFSIZE);
}
new code:
char buffer[BUFFSIZE];
Once you've done this everywhere, your LINKER should warn you if everything cannot fit into the memory available. Don't forget to reduce the heap size - but beware that some runtime io system functions may still use the heap, so you may not be able to remove it entirely.