Revised fix of memory leak #318

Based on #318 by @jasonrose, I have corrected some things that were causing me problems.