Fix memory leak with reduced variable scope