Skip to content

C++ deletes objects still referenced by Python wrappers (dangling pointers, double free) #132

Closed

Description

@vincefn

Problem

Several bound C++ methods delete sub-objects (profiles, parameters, atoms) that Python may still hold through wrappers (reference_internal). A held wrapper then dangles. With nanobind, a new object allocated at the same address can be returned as the stale wrapper, possibly with the wrong type. This is the root cause of the intermittent failure in #121. The underlying issue is that ObjCryst manages ownership manually (RegisterClient/delete) rather than with reference counting shared with Python.

Checked against vendored ObjCryst ba6ca89 with the rc0 wheel (macOS arm64, cp312, MallocScribble=1).

Confirmed crashes

Python call Deleted by C++ Result
Crystal.ConnectAtoms() merged atoms, via RemoveScatterer(atom, true) (delete is hard-coded, so SetDeleteSubObjInDestructor(false) has no effect) Python-created atoms: double free (abort). CIF atoms: segfault
RefinableObj.ResetParList() all pars (when mDeleteRefParInDestructor is true) segfault on a held GetPar()
TextureMarchDollase.DeletePhase(i) the phase's 5 pars segfault
PowderPatternDiffraction.SetReflectionProfilePar() old profile segfault
PowderPatternDiffraction.SetProfile() old profile stale or wrong-type wrapper (#121)

Deletes per the source, no crash reproduced

  • PowderPatternBackground.SetInterpPoints / ImportUserBackground / XMLInput: delete Background_Point_* pars (InitRefParList → ResetParList).
  • PowderPatternDiffraction.XMLInput: deletes the old profile when the XML's profile type differs from the current one.
  • LSQ with copy_param=True: deletes its own copied pars on re-preparation (minor).

Currently safe

  • Remove* bindings pass del=false (they leak instead of deleting).
  • Crystal::XMLInput DeleteAll: guarded by the delete flag, which is false for Python-created crystals.
  • Destructors (~Crystal, ~Molecule, ~PowderPattern, ...): child wrappers keep their parent alive.
  • Internal-only objects (mpGaussian, cctbx space group, temporaries) and functions that are not bound.

Proposed solution

  • Short term: the bindings take ownership of the old object (nb::find + nb::inst_set_state(w, true, true)), or forbid or invalidate held wrappers. ConnectAtoms must honour the del convention.
  • Long term (upstream in vincefn/objcryst): reference counting in RefinableObj via (De)RegisterClient, shared with Python through nanobind intrusive reference counting.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions