free() doesn't free memory ?

This is a followup to my post yesterday about how much memory is free. I may be missing something here, so please correct me

I'm using the code by RuggedCircuits in this thread to determine how much free memory there is. Usng that code it looks awfully like free isn't freeing memory. Here's a little test program using malloc, check_mem is RuggedCircuits code but rights a result to the serial port :

void setup() { Serial.begin(9600); check_mem(); char *Buff= (char *)malloc(200); check_mem(); free(Buff); check_mem();


The output is here:

fr mem 794 fr mem 592 fr mem 592

As you can see after free is called, the amount of free memory hasn't increased.

Any idea whats going on here ?

Many thanks


The code I posted just showed how much space was available to begin with and not yet grabbed by malloc. If you want a more accurate picture, it gets more complicated because the memory being managed by malloc has “holes” depending upon how you called malloc/free. So you might have 2000 bytes free, but it is broken up into chunks (after several calls to malloc/free) such that you can’t allocate any chunk bigger than 100 bytes (for example).

Here is an updated version of the code that returns the total amount of free space, including space under management by malloc, as well as a second return value (passed by pointer) that returns the biggest chunk of memory you can allocate with malloc right now.

#include <inttypes.h>
#include <stdlib.h>
#include <avr/io.h>

struct __freelist {
    size_t sz;
    struct __freelist *nx;

extern char * const __brkval;
extern struct __freelist *__flp; 

uint16_t freeMem(uint16_t *biggest)
  char *brkval;
  char *cp;
  unsigned freeSpace;
  struct __freelist *fp1, *fp2;

  brkval = __brkval;
  if (brkval == 0) {
    brkval = __malloc_heap_start;
  cp = __malloc_heap_end;
  if (cp == 0) {
    cp = ((char *)AVR_STACK_POINTER_REG) - __malloc_margin;
  if (cp <= brkval) return 0;

  freeSpace = cp - brkval;

  for (*biggest = 0, fp1 = __flp, fp2 = 0;
     fp2 = fp1, fp1 = fp1->nx) {
    if (fp1->sz > *biggest) *biggest = fp1->sz;
    freeSpace += fp1->sz;

  return freeSpace;

Again…only tested with AVR-LIBC version 1.6.6

Once again,

many thanks for that code. I had thought that ight be the problem ! Now to get on with the debugging.