moved buffer allocaton outside of loop