Fix a major bug in stream allocation and a potential memory leak