3

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
Matt Stevens
  • 1,104
  • 1
  • 12
  • 24
  • The link below compares different memory management approaches in FreeRTOS. Some known issues about malloc are discussed.It may help you http://www.freertos.org/a00111.html – Claudi Sep 13 '14 at 09:23
  • Ta, that was my source for figuring out how to fix my bug, but it does not explain the behaviour I observed. – Matt Stevens Sep 13 '14 at 09:28
  • "My guess is that the first and only use of malloc in this application" What application? Please post the code. Otherwise the question is too broad and will only lead to speculation. – Lundin Sep 29 '14 at 06:36
  • So, what `malloc()` was being used before you switched to `pvPortMalloc()`? Also, it's not clear exactly what problem your application was having when it used `malloc()` (whichever version fo `malloc()` that was. – Michael Burr Sep 29 '14 at 07:37
  • Refer to the FreeRTOS link above for the RTOS website and http://sourceforge.net/projects/freertos/ for their code. That aside, it is not their implementation, but how the C compiler behaves that I am interested in. – Matt Stevens Sep 29 '14 at 10:59

1 Answers1

4

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.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Ok, ta. This is what I was expecting. It appears to be what FreeRTOS's pvPortMalloc is doing as well and would explain the behaviour I'm seeing. Is this version of malloc, the one used in C89? – Matt Stevens Sep 29 '14 at 11:02
  • 1
    All good John, once I knew what to look for, finding the glibc code was relatively straight forward and I have found the file you provided. Many thanks for your pointer :-) – Matt Stevens Sep 29 '14 at 11:16