Linux build fixes, fix use after free diagnosed by valgrind