Shop OBEX P1 Docs P2 Docs Learn Events
toString causing memory leaks! — Parallax Forums

toString causing memory leaks!

ramman345ramman345 Posts: 24
edited 2007-08-09 14:03 in General Discussion
Hey guys, I'm new to the Javelin and have been using it for a few months. As I've begun more serious testing of my work I discovered that the program halts at the same place after 10-20 minutes. Using the stamp.core.Memory.freeMemory() method suggested in one of the older posts I have worked my program down to the basics of:

while(true)
{
Clear_LCD();
free_memory = stamp.core.Memory.freeMemory();
LCDtx.sendString(Integer.toString(free_memory));
CPU.delay(10000);
}

Each iteration of this loop looses 16 bytes! I think the culprit is the Integer.toString(). Any suggestions or work arounds?
Thanks

Comments

  • Peter VerkaikPeter Verkaik Posts: 3,956
    edited 2007-08-09 05:12
    The easiest way is to use a StringBuffer object.

    StringBuffer buf = new StringBuffer();
    while(true)
    {
    Clear_LCD();
    buf.clear();
    free_memory = stamp.core.Memory.freeMemory();
    buf.append(free_memory);
    LCDtx.sendString(buf);
    CPU.delay(10000);
    }

    It is required that your LCDtx.sendString() method accepts a StringBuffer as parameter.
    If it doesn't, you must make a method LCDtx.sendString(StringBuf s).

    regards peter
  • ramman345ramman345 Posts: 24
    edited 2007-08-09 12:56
    Peter, LCDtx is a UART VP object. I am using the built in sendString method of the UART class which I don't believe accepts stringBuffers. Any advice?
  • Peter VerkaikPeter Verkaik Posts: 3,956
    edited 2007-08-09 13:34
    Add following method to your program

    public void lcdSendString(StringBuffer s) {
    · int i=s.Length; int j=0;
    · while (i > 0) {
    ··· LCDtx.sendByte(s.charAt(j));
    ··· j++;
    ··· i--;
    · }
    }

    and in your program use
    lcdSendString(buf);


    regards peter
  • ramman345ramman345 Posts: 24
    edited 2007-08-09 14:03
    Peter, I have done some more testing after following your advice and made the following discovery:

    for a StringBuffer s, s.toString() does not use any memory.
    for an int i, Integer.toString(i) uses at least 16 bytes of memory every time it is called.

    Therefore I have found a compromise between our two codes:

    while(true)
    {
    Clear_LCD();
    free_memory = stamp.core.Memory.freeMemory();
    s.clear();
    s.append("Memory: ");
    s.append(free_memory);
    LCDtx.sendString(s.toString());
    CPU.delay(10000);
    }

    which does not result in memory loss. Thanks so much for your help, J
Sign In or Register to comment.