Adding a wait(1) before level_free() fixed the issue.
Normally not, otherwise we'd named the function not "wait()", but "fixbug()". If a wait(1) changes the behavior of a bug and you don't know why, it can give a hint where to look for the bug. But it's normally not a fix.