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
The usual approach would be to fill the memory with a known pattern and then to check which areas are overwritten.
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.