views:

290

answers:

2

Hi there,

Programming for my Arduino (in some kind of mix of C/C++), I noticed something weird.

Everytime I communicate through the serial port, I keep an eye on the SRAM usage. Normally, it ranges between 300~400 bytes. However, after adding a new routine (see below), I noticed it always jumped from 300~400 bytes of free memory to EXACTLY 1023. My hunch is that there's a problem.

This is the new routine

void NewRoutine(char *cmdd){

   GSM.print(cmdd);
   GSM.print(26, BYTE);
   GSM.print(endl); // <-- added later
   Serial.print(availableMemory());
}

And this is the MemoryCheck Routine

  int availableMemory() {
  int size = 1024;
  byte *buf;
  while ((buf = (byte *) malloc(--size)) == NULL);
  free(buf);
  return size;
}

Please note this: First, it didn't work. After I added the endl command, it worked magically, but then I noticed the memory issue.

Anyone got ideas for a workaround?

A: 

Maybe it holds a buffer on the heap to transfer data to the serial port?

Blindy
You're right, it's on the heap because accessing the cmdd variable is time consuming. So I assign it far before I actually need it - thus it's on the heap.
+6  A: 

The reason you're getting 1023 bytes of free memory is purely because the malloc (on 1023 - which is --1024) is succeeding on the first try. This means you have at least 1023 bytes of memory - but doesn't tell you the true available memory.

Prior to this, you must have had something keeping memory around. My guess is the GSM class here - it probably holds the data (cmdd + 26) in an internal buffer which is flushed on a newline. As soon as you added your endl call, you're probably getting the full memory back from the buffer.

How large is your command? My guess is that it (or the full set of them) is probably around 700 bytes...

Reed Copsey
Actually, cmdd is an array of chars (a string, if you may) of 14 chars long. So basically there's a lot of other variables around not associated with cmd. Maximum available SRAM is 1kb, so indeed I guess I have around 700 bytes of data.Is there a way of getting the true available memory? After NewRoutine(), whenever I call other functions, availableMemory still returns 1023.
endl is both "\n" and flush() using C++ STL ostreams - perhaps the same here. Buffering sounds like a likely cause for any "strange" memory usage or output delays
Tom Leys
@Mike: Have you tried, just for grins, seeing what happens when you allocate >1023 bytes? Have you verified that it's actually failing correctly?
Reed Copsey