I'm trying to diagnose a malloc nightware in STM32 CubeIDE.
Edit: This was nothing to do with malloc!
It was a debugging bug caused my mixing HAL libraries, see message 3!
The bug caused the code shown at the IDE to not match the code running at the CPU, or either it was doing something really weird, nothing made sense at all, stepping the code jumped between different completely random functions.
Removing the unused STM32xxx_HAL folder fixed it.
Every call to malloc/free also updates a global mallinfo() struct, so I can debug the memory usage in realtime.
I can allocate about 9KB in previous steps of the program and then free it. mallinfo reports 9KB used, then 9KB available.
Later, calling for ~2KB, everything fails and I get into the Hardfault handler.
Before allocation, mallinfo() reports 9KB free, going down to 7KB after it, meaning it's actually allocating that amount.
But malloc is returning 0xFFFFFFFF (The famous (void *)-1 ?), while others return a correct value (0x2000...., somehere in RAM).
The same code works in a 32F101 with less ram (10KB), but fails in a 32F072 with larger ram (16KB), there's no special assembly code else than few nops.
The code is too large and won't without optimizations, so I applied -Og globally (optimize for debugging), the disabled function optimization and inlining with gcc attributes.
I recall this worked last time I did it, but debugging this function keeps doing nosense behavior/jumping like when optimized, stepping any of these nops will randomly spawn the cursor at other functions/areas, so I'm unable to properly debug it.
Neither do pP appear on the variables scope.
It's driving me nuts! Any ideas?
Ultimately I disabled 70% of the code and ran the whole thing with -O0. Still doing the same thing!
Code enters the function, but the next steps will "travel" to a GPIO function, to HAL_GetTick, to the ADC...!
__attribute__ ((noinline)) __attribute__((optimize("O0")))
void allocTest(void) {
uint32_t *pP;
asm("nop");
pP = malloc(sizeof(something_t));
if( pP==NULL )
asm("nop");
else if( pP==(void*)-1 )
asm("nop");
else{
asm("nop");
free(pP);
}
}