Fix some buffer and memory leaks