Fix looping read/write bug, and leaked buffer bug