Jack String class memory leak

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Jack String class memory leak

dd-b
At least, using a string literal 500 times in a loop causes a heap exhaustion error.  Since I'm assigning the same constant to the same variable over and over, that looks like it should be okay to me.  (It also happens if I call Output.printString on the same string literal, instead of assigning it to a string variable).  

The attached Main.jack file produces the problem -- either with the "let s=<stringlit>" statement as it is now, or with that commented out and the "output.printString(<stringlit>)" statement uncommented.

Main.jack
Reply | Threaded
Open this post in threaded view
|

Re: Jack String class memory leak

cadet1620
Administrator
dd-b wrote
At least, using a string literal 500 times in a loop causes a heap exhaustion error.  Since I'm assigning the same constant to the same variable over and over, that looks like it should be okay to me.  (It also happens if I call Output.printString on the same string literal, instead of assigning it to a string variable).
Because the VM language does not have any concept of multi-word data constants, the only way to make a string constant is programatically. The expression
    let str = "abc"
in Jack compiles to the equivalent of
    let str = String.new(3);
    do str.appendChar(65);    // 'a'
    do str.appendChar(66);    // 'b'
    do str.appendChar(67);    // 'c'
Thus, every time that a string constant is "executed", a new String object is allocated. You, the programmer, must deallocate this String.

The only way to do this is to assign the constant to a String variable, pass the variable to Output.printString, and then destroy it.

For constants that are used a lot, like a ", " list separator, you might want to make a static class variable that gets set to the constant value in your class's constructor, and then you can use that variable throughout your class.

--Mark