fix segfault due to using a variable that was just freed