This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Why do we need size as the last parameter for Memory_free

Hi, experts,

   The last parameter for Memory_free is size, but I wonder why we need size? We know standand C function "free" doesn't need size as a parameter, because the size is saved in somewhere in the header of the allocated buffer.

   If we pass a size that is different from the size we passed to "Memory_alloc", what will happen? For example, if we pass a smaller size than allocated, can we still use the reset of the buffer?

  Thanks

  • Hello,

    You are correct that free does not take a size because it stores in the "hidden" space before the buffer. Memory_alloc does not store the size in the buffer. Memory_alloc  supports an alignment request. Storing the size before the buffer is detrimental to alignment and fragmentation. Alignment request are common in embedded systems when dealing with DMA, caches, peripherals, etc.

    Passing in the wrong size generally causes bad things. It really depends on the heap you are using (e.g. HeapMem, HeapBuf, etc.). In theory, if you are using HeapMem (the default heap unless you ask for a different one), you could pass a smaller size and keep the rest of the buffer. For example, if you allocated 128 bytes, you could pass in 32 to the free and keep using the last 96 bytes (and evidentally free it also). We do not recommend this though! The Memory_alloc/Memory_free does some alignment management, that must be accounted for.  This management could change in a release, so your code might work in one version, but not another.

    Todd

  • Thank you very much.