Search code examples
cmemory-managementmallocheap-memoryfreertos

First use of malloc sets up the heap?


I had a bug which I have now fixed but which I need to explain in a report.

I am working on an embedded device running FreeRTOS which does its own heap memory management. FreeRTOS has its own version of malloc(), pvPortMalloc() which I was unaware of and using it fixed the memory issues I was having.

My question relates to the size of the memory overflow that was caused by malloc(), the data was only 8 bytes in size, the size of the overflow however was significant, kilobytes if not larger. My guess is that the first and only use of malloc in this application, set up a second heap in competition with FreeRTOS's heap, of at least several kb is size.

Can anyone confirm this or give a better explanation. Pointers to more info or references greatly appreciated.


Solution

  • It is a common trait of many malloc implementations to request a larger chunk of memory from the system than is needed for a single request. For example, glibc's ptmalloc has this:

    #define MINIMUM_MORECORE_SIZE  (64 * 1024)
    

    This serves as a lower bound on the amount of memory (in bytes) to request from the OS (via sbrk()) at a single time. So you would expect to see a single tiny allocation result in 64 KB "used."

    One reason to do this sort of thing is to reduce system calls; another might be to reduce fragmentation.