1
votes

I am developing an application with STM32L476 (without FreeRTOS). I am using SW4STM32 and STM32CubeMx. I am using SDMMC with Fatfs in my application. Currently I am seeing a hardfault when I free memory.

These are my stack and heap details as per linker file

/* Highest address of the user mode stack */
_estack = 0x20018000;    /* end of RAM */
/* Generate a link error if heap and stack don't fit into RAM */
_Min_Heap_Size = 0x7E20;      /* required amount of heap  */
_Min_Stack_Size = 0x1FA0; /* required amount of stack */

0x20003248 is the address at which crash occurs (is the address which I am freeing)

I tried to debug the issue by following this link Cortex-M3 Hard Fault - find cause

This is what I get at hardfault:

SCB->HFSR = 0x40000000
Forced Hard Fault
SCB->CFSR = 0x00008200

but I couldnt conclude anything

1
This page includes a description of all the CFSR register bit values. You have BFARVALID and PRECISERR set. Read the descriptions and then examine the BFAR register value.kkrambo

1 Answers

3
votes

HardFaults like this - in free or even malloc - usually indicate a problem with your memory being corrupted in some way. The most common cause is either double free on the same memory address or overwriting data in memory, e.g. writing past the end of some kind of buffer.

Regarding the second point - although this is implementation dependent - the general approach for malloc is to store some additional information that it uses internally for future calls to malloc or free. These are things like size of the chunk that actually got allocated, information about next chunk in memory etc. This information in the implementation I've checked was stored right before the memory address you're given as a return value from malloc. If you then overwrite this data - for example by writing past a buffer that got allocated before this address - the next call to free that frees this memory is going to fail in unexpected ways, often resulting in a HardFault.

Having said that and given the limited information you've provided, all I can suggest is to go through the code that writes data to memory - mostly code writing to arrays allocated with malloc. Limit the code to a minimal case that still causes HardFault and debug it. Possibly set some data breakpoints (write). free failing when freeing memory may not (and in this case, it likely doesn't) necessarily indicate a problem with that particular portion of memory, but rather an adjacent one.