How to free up memory from a sound.track?

I keep re-using the same variable noteTrack to play different synth note sequences. Example:

noteTrack = pd.sound.track.new()
noteTrack:setInstrument(instrument)
noteTrack:addNote(step, note, 1)

But memory is consumed every time I do that, slowly filling all RAM. pd.sound.track.new() is clearly not sufficient to clear the track and remove the previous contents from memory.

If I do NOT clear the track with pd.sound.track.new() then unwanted notes keep piling up of course... yet oddly there's no perceptible memory leak. Seems backwards!

What's the proper way to clear the track for re-use that won't leak memory?

TIA!

Oops, there's a memory leak there. :frowning: The Lua destructor isn't cleaning up the track, so that's 2KB of note list memory lost each time. But noteTrack:clearNotes() should do what you want. One tiny implementation detail I notice there: clearNotes() frees the note storage every time, even though the initializer pre-allocates 2KB of storage. That means in your case it's freeing then reallocating the same memory every time. I should instead have clearNotes() shrink it to 2KB if it's bigger, otherwise do nothing but change the number of notes to 0. Nope, I'm wrong, the buffer isn't allocated until you add the first note.

1 Like

Cool, thanks! In practice, it was unlikely to ever build to the point of a crash. But I wanted to be tidy, and now I can!

1 Like