seniorRuby

How does CRuby maintain memory safety between the VM, GC, and native C extensions?

Updated May 17, 2026

Short answer

CRuby uses GC write barriers, object marking rules, and controlled APIs (like rb_gc_mark) to ensure native extensions remain safe.

Deep explanation

CRuby must coordinate three memory domains: VM-managed Ruby objects, GC heap, and C extensions. Native extensions are required to explicitly mark Ruby objects they reference using rb_gc_mark during GC cycles. If they fail, objects may be prematurely collected. The GC uses a mark-and-sweep algorithm with write barriers to track cross-generation references. The VM enforces object validity via VALUE handles, which are abstracted pointers with embedded tagging.

Unlock with a Pro subscription to view this section.

View pricing

Real-world example

No real-world example available yet.

Unlock with a Pro subscription to view this section.

Upgrade to Pro

Common mistakes

No common mistakes listed yet.

Unlock with a Pro subscription to view this section.

Upgrade to Pro

Follow-up questions

No follow-up questions available yet.

Unlock with a Pro subscription to view this section.

Upgrade to Pro

More Ruby interview questions

View all →