Any objects not intended to be collected must be pointed to either from other such accessible objects, or from the registers, stack, data, or statically allocated bss segments.
The Test::Outer and Test::Inner Crystal wrappers are always GC-enabled, so they should be collected as no Crystal variables point to them. This leaves only the actual Outer and Inner instances on the C++ side. Now the Inner instance:
is GC-enabled (because the generated _CONSTRUCT function invokes the UseGC allocator);
is pointed to from Outer::last_, but this doesn't make it accessible because Outer::last_ itself is unmanaged (the C++ wrapper for Outer::new_no_gc simply forwards the returned pointer);
is no longer pointed to from the managed Test::Inner instance.
Thus, it too will be collected despite being indirectly traceable through Outer::last_->inside. The last line therefore refers to a potentially deleted object, and I managed to get this snippet to crash by enlarging the Inner struct and repeating the collection step multiple times.
In this particular case, we could simply add UseGC to all occurrences of the default new operator, or use GC_malloc_uncollectable for Outer instead (the instance itself will be unmanaged, but its inside member is considered by the GC). This is clearly not possible if only the library and header files are available to Bindgen.
Consider these snippets:
Boehm GC's readme states:
The
Test::Outer
andTest::Inner
Crystal wrappers are always GC-enabled, so they should be collected as no Crystal variables point to them. This leaves only the actualOuter
andInner
instances on the C++ side. Now theInner
instance:_CONSTRUCT
function invokes theUseGC
allocator);Outer::last_
, but this doesn't make it accessible becauseOuter::last_
itself is unmanaged (the C++ wrapper forOuter::new_no_gc
simply forwards the returned pointer);Test::Inner
instance.Thus, it too will be collected despite being indirectly traceable through
Outer::last_->inside
. The last line therefore refers to a potentially deleted object, and I managed to get this snippet to crash by enlarging theInner
struct and repeating the collection step multiple times.In this particular case, we could simply add
UseGC
to all occurrences of the defaultnew
operator, or useGC_malloc_uncollectable
forOuter
instead (the instance itself will be unmanaged, but itsinside
member is considered by the GC). This is clearly not possible if only the library and header files are available to Bindgen.Qt5.cr is also prone to this issue. Example: