Fix output cleanup that could lead to segfaults