Fix a nasty memory leak

Thanks to yi huang for putting me on the right track to finding this.