FreeRTOS / FreeRTOS-Kernel

FreeRTOS kernel files only, submoduled into https://github.com/FreeRTOS/FreeRTOS and various other repos.
https://www.FreeRTOS.org
MIT License
2.51k stars 1.05k forks source link

[BUG]traceMALLOC() memory count is inaccurate #1078

Closed DazzlingOkami closed 3 weeks ago

DazzlingOkami commented 1 month ago

Describe the bug In the implementation of heap4.

Use traceMALLOC() to track that the number of memory bytes allocated is less than the actual amount allocated. At the same time, it will cause the count of traceMALLOC() and traceFREE() to be unequal.

When searching for an available free block, if the remaining length after partitioning is too short, the free block is not split, resulting in the actual allocated memory length being greater than xWantedSize. However, traceMALLOC() seems to ignore this and xWantedSize has not been adjusted appropriately.

Target

To Reproduce Construct test code:

// hook to freertos kernel
#define traceMALLOC( pvAddress, uiSize ) trace_malloc(pvAddress, uiSize)
#define traceFREE( pvAddress, uiSize )   trace_free(pvAddress, uiSize)
static int trace_enable = 0;
static uint32_t malloc_total = 0;
static uint32_t free_total = 0;

void trace_malloc(void *ptr, uint32_t size){
    if(trace_enable){
        printf("=malloc= %p, %lu\r\n", ptr, size);
        malloc_total += size;
    }
}

void trace_free(void *ptr, uint32_t size){
    if(trace_enable){
        printf("= free = %p, %lu\r\n", ptr, size);
        free_total += size;
    }
}

int test_unit(void){
    trace_enable = 1;

    void *p1 = pvPortMalloc(1016);
    void *p2 = pvPortMalloc(1016);
    void *p3 = pvPortMalloc(1016);

    vPortFree(p2);

    p2 = pvPortMalloc(1008);

    vPortFree(p1);
    vPortFree(p2);
    vPortFree(p3);

    trace_enable = 0;

    printf("malloc total: %lu\r\n", malloc_total);
    printf(" free  total: %lu\r\n", free_total);

    return 0;
}

output log:

=malloc= 0x2401b2a0, 1024
=malloc= 0x2401b6a0, 1024
=malloc= 0x2401baa0, 1024
= free = 0x2401b6a0, 1024
=malloc= 0x2401b6a0, 1016
= free = 0x2401b2a0, 1024
= free = 0x2401b6a0, 1024
= free = 0x2401baa0, 1024
malloc total: 4088
 free  total: 4096

clearly seen that the total number is not equal.

Expected behavior The total number of allocations and releases should be equal.

Additional context Consider modifying xWantedSize to the size of a free block when not split blocks.

shubnil commented 4 weeks ago

Hi @DazzlingOkami , Thanks for raising the bug. Will it be ok for you to create a PR as well for the same.

DazzlingOkami commented 3 weeks ago

I will try to fix it.

kar-rahul-aws commented 3 weeks ago

Thanks @DazzlingOkami for the contribution ! The PR #1089 has been verified to solve the aforementioned issue , approved and merged in the main code.