Let's Make Robots!

Arduino memory usage

All,

I am doing some tests to try to understand how C++ impacts available memory in the Arduino.  I am profiling some code I have written and trying

to understand the impact of allocating objects on the stack with the new command (which traditionally uses malloc or one of its derivations under

the hood - is that true with the gcc compiler?).  As I understand it, the Arduino has

32k program memory - the program size it shows in the UI for the Arduino - Binary sketch size: 14,218 bytes (of a 32,256 byte maximum)2k sram -

which shares the stack and any program memory allocated ( ie int t = 20 ; t is allocated here).
1k eeprom - can put storage here -- reading and writing will be slow to this memory -- not important to this testing since I want fast access.


I found the memoryTest() code somewhere online.  Offhand, this seems it should work and should be accurate, but not sure.  I know this would work

with a PC, but not sure with an Arduino.

// this function will return the number of bytes currently free in RAM
int memoryTest() {
  int byteCounter = 0; // initialize a counter
  byte *byteArray; // create a pointer to a byte array
  // More on pointers here: http://en.wikipedia.org/wiki/Pointer#C_pointers

  // use the malloc function to repeatedly attempt allocating a certain number of bytes to memory
  // More on malloc here: http://en.wikipedia.org/wiki/Malloc
  while ( (byteArray = (byte*) malloc (byteCounter * sizeof(byte))) != NULL ) {
    byteCounter++; // if allocation was successful, then up the count for the next try
    free(byteArray); // free memory after allocating it
  }
 
  free(byteArray); // also free memory after the function finishes
  return byteCounter; // send back the highest number of bytes successfully allocated
}


char * array = char(1024);


void setup()
{
  Serial.begin(9600) ;
 
  Serial.println(memoryTest());
}
 
void loop()
{

 
 
}

If I run this, I get 638 back from the memoryTest() call.  If I remove the array allocation, I get 1278 as available sram. I have tried a number

of different allocations using the C++ new command, and no matter what allocations I use, I either get back 638 or 1278 for available sram.  I am

sure it allocates memory in large chunks but was hoping there was an expert on how the gcc compiler manages memory.

a
char * array = char(2048);

definitely fails returns null as you would expect. 

char * array = char(1024);

will succeed but then the memoryTest() will return 1278 which would seem inaccurate.  Something weird going on here.  Any ideas?

Regards,

Bill

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

I found this "freeRAM()" function a while ago maybe it can help?

http://jeelabs.org/2011/05/22/atmega-memory-use/

Will have to compare this versus what I am using and see if they agree.  Great to have in the developer's quiver as it were.  Thanks!