2021-03-16 10:08 AM
I'm using cJSON on a STM32F401 and I'm a bit worried with possible problems regarding with memory allocation.
If a call malloc(1) (so asking the heap for 1 byte only) how many bytes are really used on the Heap?
I would assume correct answer with be 16 bytes used.
if I call malloc(5) 16 bytes are used.
if I call malloc(16) 16 bytes are used.
if I call malloc(17) 32 bytes are used.
If somebody knows the right answer please let me know.
I cannot enter malloc on STM32CudeIDE since it seems to be built into a library...
thanks,
Eduardo
2021-03-16 11:09 AM
I'd expect it to be more, the memory address returned is preceded by a linked-list structure the heap allocator uses to manage the memory arena.
Check the allocator code.
2021-03-16 12:18 PM
That is indeed a good point.
I was asking for the minimum unit of allocation which I think is 16 bytes.
But you are right, there is a header with pointers (next and previous) and the size of the block given...
So if one allocates small strings it could become a waste of space... =)
2021-03-16 01:13 PM
There are usually one or more free lists linking only the freed blocks of the heap (and using the freed blocks themselves for its data structure which mainly determines the allocation granularity). The currently allocated blocks are not individually linked. You can print out the addresses returned from malloc or call sbrk(0). The latter returns the top of currently used heap (including free blocks). This should give you an idea. Note that an increasing number of freed blocks in those lists causes an increasing run-time for free block searching too.
The implementation is open source and should be close to this one: https://sourceware.org/git/?p=newlib-cygwin.git;a=blob;f=newlib/libc/stdlib/mallocr.c;h=ecc445f3d36365a4840e31c737db5018ddba42e9;hb=fffd2770db9aa7aa0404d124d8ce4bf00f7f4c71
hth
KnarfB