Hi,
I hope this question will make sense, as my brain is currently still a bit fried after debugging an annoying issue (in our own code, of course).
The problem we caused is that we allocated memory in FreeRTOS heap, and wrote outside the buffer. Just one byte though. But that’s enough to create really hard to track issues :).
What happened in some details:
- at some point (early in startup of our app) we wrote outside a buffer in FreeRTOS heap
- a while later, once our product is online through modem/eth, I print some FreeRTOS heap stats
That resulted in a MemManage fault.
After 4 hours, I finally found the problem in our own code, but I found it by adding this in the pvPortMalloc
void * pvPortMalloc( size_t xWantedSize )
{
/* If malloc is called for size zero, we don't have to do anything */
if (xWantedSize == 0)
{
return NULL;
}
BlockLink_t * pxBlock;
BlockLink_t * pxPreviousBlock;
BlockLink_t * pxNewBlockLink;
void * pvReturn = NULL;
size_t xAdditionalRequiredSize;
vTaskSuspendAll();
{
// Poor mans solution to force the mem man fault earlier.... I hope...
HeapStats_t xHeapStats;
vPortGetHeapStats(&xHeapStats );
This worked, lucky me. So I completely understand that this is not a guarantee, because the GetHeapStats will hard fault between two mallocs. One malloc will corrupt the FreeRTOS heap, and afterwards the GetHeapStats might explode. I realize while typing, a better place for this check would probably be AFTER marking the block as used, then I might have a chance of immediately getting the hard fault.
Anyway, my question is, can you think of a better way to (probably conditionally on a FreeRTOS config compiled option) of doing this check.
What happens in my case, is that one byte of the next blocks administration is written to 0x0
, which has a fair chance of causing a hardfault when iterating over all free blocks. But I can think of many situations where it would still go unnoticed.
I am trying to find some mechanism which will fire when memory corruption is detected. Maybe it would be nice to enable/disable this check for performance reasons (although in our case, we are not super time critical, some extra check on alloc won’t be visible in our application’s performance anyway).
Could you advise me anything? Or is there maybe something already in more recent FreeRTOS releases? I am on V10.6.1.
Hope this question makes any sense at all
Thanks for any advice
Best regards, Bas