remove unnecessary mallocs, add scope guards