Fixes several memory leaks and use after free / segfaults waiting to happen.