Fix freeing invalid pointers