Fix and test potential OOM and memory leak