cancel
Showing results for 
Search instead for 
Did you mean: 

malloc(1)

EGonc.1
Associate II

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

3 REPLIES 3

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.

Tips, buy me a coffee, or three.. PayPal Venmo Up vote any posts that you find helpful, it shows what's working..
EGonc.1
Associate II

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... =)

KnarfB
Principal III

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