Memory usage statistics

Hi,
Does anyone have any code snippets for getting the amount of memory in use and also the total size of the memory dynamically? I've found the links to the AVR way, but couldn't find much for the Due.

Thanks,
Greg

I would find this useful too.

Seconded

Hi Greg,

do you have the link about the AVR way?

AVR function:

// Returns the number of bytes currently free in RAM
static int freeRAM(void) 
{
 extern int  __bss_end;
 extern int* __brkval;
 int free_memory;
 if (reinterpret_cast<int>(__brkval) == 0) {
   free_memory = reinterpret_cast<int>(&free_memory) - reinterpret_cast<int>(&__bss_end);
 } else  {
   free_memory = reinterpret_cast<int>(&free_memory) - reinterpret_cast<int>(__brkval);
 }
 return free_memory;
}

The Due seems to be using Newlib: The Newlib Homepage There are a few functions and symbols relating to used and free memory. Ram organization appears unix-like. Here is a quick sketch as a starting point:

// Due free ram by stimmer - needs more testing

#include <malloc.h>
#include <stdlib.h>
#include <stdio.h>

//these might be defined in headers somewhere but I can't find where.
extern char _end;
extern "C" char *sbrk(int i);
char *ramstart=(char *)0x20070000;
char *ramend=(char *)0x20088000;


int dummy[42]={1,2,3};
void setup() {
  dummy[6]=9;
  Serial.begin(9600);
}

int total=0;
int count=0;
void loop() {
  int r=random(1,100)*8;
  char *memoryalloc=(char *)malloc(r);
  char *memoryleak =(char *)malloc(r);
  free(memoryalloc);
  total+=r;
  count+=1;
  printf("\nI have malloced %d\n",total);
  printf("total+8*count = %d\n",total+8*count);

  printf("\nmalloc_stats():\n");
  malloc_stats();  
  
  struct mallinfo mi=mallinfo();

  printf("\nmallinfo():\n");  
  printf("    arena=%d\n",mi.arena);
  printf("  ordblks=%d\n",mi.ordblks);
  printf(" uordblks=%d\n",mi.uordblks);
  printf(" fordblks=%d\n",mi.fordblks);
  printf(" keepcost=%d\n",mi.keepcost);
  
  char *heapend=sbrk(0);
  register char * stack_ptr asm ("sp");
//char *stack_ptr=(char *)alloca(0); // also works

  printf("\nram start %lx\n", ramstart);
  printf("data/bss end %lx\n", &_end);   
  printf("heap end %lx\n", heapend); 
  printf("stack ptr %lx\n",stack_ptr);  
  printf("ram end %lx\n", ramend);
  
  printf("\nDynamic ram used: %d\n",mi.uordblks);
  printf("Program static ram used %d\n",&_end - ramstart); 
  printf("Stack ram used %d\n\n",ramend - stack_ptr); 
  printf("My guess at free mem: %d\n",stack_ptr - heapend + mi.fordblks); 

  delay(1000);
}