Fix potential memory leak and reading unitialized memory