Malloc failed in with pic32MX port

Hello, Sometimes when I try to allocate 2048 bytes using pvPortMalloc() it fails and reported that remaining space heap size is greated then 11k in the vApplicationMallocFailedHook() I use heap4.c and I can’t really find an explanation for this ? Regards Chaabane

Malloc failed in with pic32MX port

One danger with using heap memory is that the heap space can become fragmented and hard to find large blocks. For instance, if you allocate a number of 1k blocks, then release every other one, the space left normally can’t be used to allocate a 2k block. This is one reason many coding standards restrict the use of heap memory to startup and ‘non-critical’ operations that are allowed to ‘fail’.

Malloc failed in with pic32MX port

I have allocated 36k for the kernel total heap, after few allocations of 38,32,512… bytes (doesn’t exceed 4k), the pvPortMalloc() systematically failes to allocate 2K space yet it reported that it has more than 11,5K free space. I reduced the total heap to 30K and everything is working just fine now !!! Any idea why i’m having this issue ?

Malloc failed in with pic32MX port

I don’t know of any reason this should be a problem. How much RAM does your PIC32 actually have? Is anything else walking over the heap space? Is your linker script correct for your device and are any linker warnings generated?

Malloc failed in with pic32MX port

My PIC has 128K RAM and I don’t have any linker warning. What do you mean by “Is anything else walking over the heap space?” I’m not sure how to check that !!

Malloc failed in with pic32MX port

What do you mean by “Is anything else walking over the heap space?” I’m not sure how to check that !!
The heap includes some meta data that describes its state (which blocks are free, which allocated, etc.). If there is a good old fashioned data corruption by another part of the application writing over this data then the heap implementation will misbehave because the meta data will be corrupt. It might be that a certain part of your RAM is getting used by something else, either intentionally or unintentionally, and once you set the heap size large enough so it hits that RAM region, you get into problems of corruption.

Malloc failed in with pic32MX port

It could be the case, Is there a way to check this ?