Issue with using realloc()

Using arm-none-eabi-gcc on linux.

I am using realloc() on a M3 and find that it does not seem to free the unused blocks ?

Here is the sequence I use:
uint8_t a = malloc(1000); 
uint8_t b = realloc(a, 100); // at this point i expect 900 bytes free in the heap. But mallinfo() shows all 1000 in use ?
uint8_t c = malloc(100); // malloc asks for an extra 100 bytes at this point and total heap size becomes 1100 bytes.
It appears that malloc c requests for an extra 100 bytes even though the heap should have 900 bytes remaining from the realloc. Am I doing something incorrect ? 

  • You need to read the description of realloc() more carefully.
    The actual implementation will depend on your library and/or heap management code.
    Nothing in the function description guarantees you will actually free up any memory when you reduce the size you need. In fact, increasing the number of bytes you need may or may not result in a newly allocated piece of memory if the underlying memory block was already large enough on many systems. This is due to the fact that most memory allocation schemes round up in increments of a given block size.
    These optimizations are necessary on embedded systems due to considerations including performance, lack of a real garbage collection mechanism, no MMU,  and memory fragmentation.

  • Hi

    In case you are still looking for assistance with this, I have moved your post to the Cortex-M forum. If James has given you a solution, could you please mark his response as correct?


    Oli from the Community team

More questions in this forum