fixes use after free
adds safety checks