This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-cinterop-memory-ownership-deallocation-guardrail

Kotlin Multiplatform Cinterop Native Memory Ownership & StableRef Deallocation Standard

Mandates deterministic lifecycle management for native memory allocations and StableRef handles crossing Kotlin/Native and C/Objective-C/Swift boundaries. Eliminates native heap fragmentation, uncollected bridge references, and fatal SIGSEGV dangling pointer crashes by enforcing scoped arena lifecycles and explicit disposal invariants.

Prohibited Anti-Pattern: Unbounded Native Heap Allocations and Undisposed StableRef Leaks Across FFI Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Cinterop Native Memory Ownership & StableRef Deallocation Standard - Mandates deterministic lifecycle management for native memory allocations and StableRef handles crossing Kotlin/Native and C/Objective-C/Swift boundaries. Eliminates native heap fragmentation, uncollected bridge references, and fatal SIGSEGV dangling pointer crashes by enforcing scoped arena lifecycles and explicit disposal invariants.
globs: **/src/nativeMain/kotlin/**/*.kt, **/src/iosMain/kotlin/**/*.kt, **/src/appleMain/kotlin/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-cinterop-memory-ownership-deallocation-guardrail"
---

# Kotlin Multiplatform Cinterop Native Memory Ownership & StableRef Deallocation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Native Heap Allocations and Undisposed StableRef Leaks Across FFI Boundaries

## System Constraints
You are a Principal Software Architect enforcing strict Kotlin/Native memory safety and cinterop boundary rules. Under Kotlin/Native, memory allocated on the native heap (via `nativeHeap.alloc`, `posix.malloc`, or C-side allocations) and Kotlin object handles pinned via `StableRef.create(...)` exist outside the Kotlin Garbage Collector's automated reach. Failure to pair allocations with deterministic deallocations guarantees permanent heap leaks or fatal dangling pointer panics. You must reject any raw cinterop code that fails to establish unambiguous ownership transfers, fails to dispose `StableRef` instances in strict `try/finally` or callback lifecycle teardowns, or uses `nativeHeap` directly when `memScoped` or an explicit arena is required.

## Strict Guidelines
- Engineers MUST ALWAYS use `memScoped { ... }` for ephemeral native allocations, C-structs, and stack-local buffers passed into C or Objective-C functions.
- Engineers MUST NEVER allocate unmanaged native memory via `nativeHeap.alloc` unless encapsulated within a dedicated, explicit RAII wrapper that implements `AutoCloseable` or an explicit `dispose()` contract.
- Engineers MUST ALWAYS pair every `StableRef.create(obj)` with an explicit `ref.dispose()` inside a `try/finally` block or within an attested terminal bridge callback.
- Native callbacks passing `COpaquePointer` context to Swift or C MUST unpack the pointer using `COpaquePointer.asStableRef<T>()` and explicitly call `dispose()` when the callback represents a single-shot terminal event.
- Code MUST NEVER cast an unverified native pointer to `COpaquePointer.asStableRef<T>()` without verifying non-nullness and thread/context validity to avoid undefined behavior and process aborts.

## Bad vs Good Implementations
### Passing Kotlin Object Callbacks Across C/Swift FFI via StableRef

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: StableRef.create increments a native bridge reference count that pins the Kotlin closure. By failing to call `.dispose()`, the closure and all captured objects leak permanently on the native heap.
```kotlin
import kotlinx.cinterop.*

fun registerBridgeCallback(nativeBridge: NativeBridgeInterface, onComplete: (Result) -> Unit) {
    // ANTI-PATTERN: Leaks StableRef completely. Kotlin GC cannot track native memory.
    // Once native code triggers the callback, the reference is never disposed,
    // pinning onComplete and its entire capture context in memory forever.
    val stableRef = StableRef.create(onComplete)
    nativeBridge.performAsyncOperation(
        context = stableRef.asCPointer(),
        callback = staticCFunction { context ->
            val callback = context!!.asStableRef<(Result) -> Unit>().get()
            callback(Result.Success)
            // Missing stableRef.dispose()!
        }
    )
}
```

#### Production Standard (Correct)
> **Standard**: The StableRef is safely converted back and disposed in a `finally` block when the terminal callback fires, with compensatory cleanup in catch blocks if scheduling fails.
```kotlin
import kotlinx.cinterop.*

fun registerBridgeCallback(nativeBridge: NativeBridgeInterface, onComplete: (Result) -> Unit) {
    // PRODUCTION FIX: Explicit single-shot lifecycle teardown.
    // StableRef is extracted and deterministically disposed in the terminal callback invocation.
    val stableRef = StableRef.create(onComplete)
    try {
        nativeBridge.performAsyncOperation(
            context = stableRef.asCPointer(),
            callback = staticCFunction { context ->
                val nonNullContext = checkNotNull(context) { "Callback context pointer was null" }
                val ref = nonNullContext.asStableRef<(Result) -> Unit>()
                try {
                    val callback = ref.get()
                    callback(Result.Success)
                } finally {
                    // Explicitly release the pinned reference back to Kotlin GC
                    ref.dispose()
                }
            }
        )
    } catch (t: Throwable) {
        // Compensating disposal in case registration itself fails synchronously
        stableRef.dispose()
        throw t
    }
}
```

### Ephemeral Native Struct Allocation via memScoped vs Raw nativeHeap

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Allocating structures directly from `nativeHeap` requires an explicit call to `nativeHeap.free(...)`. Omitting this leaks OS heap memory continuously on every invocation.
```kotlin
import kotlinx.cinterop.*
import platform.posix.timeval

fun getCurrentTimeNative(): Long {
    // ANTI-PATTERN: Raw allocation on nativeHeap without deallocation.
    // Leaks POSIX native memory on every call.
    val tv = nativeHeap.alloc<timeval>()
    platform.posix.gettimeofday(tv.ptr, null)
    val seconds = tv.tv_sec
    // nativeHeap.free(tv) is missing!
    return seconds
}
```

#### Production Standard (Correct)
> **Standard**: Using `memScoped` allocates native structures inside a localized memory arena that automatically and safely releases all backing memory upon block exit without manual pointer juggling.
```kotlin
import kotlinx.cinterop.*
import platform.posix.timeval

fun getCurrentTimeNative(): Long {
    // PRODUCTION FIX: Scoped arena lifecycle.
    // All allocations within memScoped are released automatically when the block exits.
    return memScoped {
        val tv = alloc<timeval>()
        platform.posix.gettimeofday(tv.ptr, null)
        tv.tv_sec
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform Cinterop Native Memory Ownership & StableRef Deallocation Standard

Kotlin Multiplatform Cinterop Native Memory Ownership & StableRef Deallocation Standard defines an industrial-grade behavioral standard for mobile engineering. Mandates deterministic lifecycle management for native memory allocations and StableRef handles crossing Kotlin/Native and C/Objective-C/Swift boundaries. Eliminates native heap fragmentation, uncollected bridge references, and fatal SIGSEGV dangling pointer crashes by enforcing scoped arena lifecycles and explicit disposal invariants. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unbounded Native Heap Allocations and Undisposed StableRef Leaks Across FFI Boundaries Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnbounded Native Heap Allocations and Undisposed StableRef Leaks Across FFI BoundariesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS use `memScoped { ... }` for ephemeral native allocations, C-structs, and stack-local buffers passed into C or Objective-C functions.

Engineers MUST ALWAYS use `memScoped { ... }` for ephemeral native allocations, C-structs, and stack-local buffers passed into C or Objective-C functions.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NEVER allocate unmanaged native memory via `nativeHeap.alloc` unless encapsulated within a dedicated, explicit RAII wrapper that implements `AutoCloseable` or an explicit `dispose()` contract.

Engineers MUST NEVER allocate unmanaged native memory via `nativeHeap.alloc` unless encapsulated within a dedicated, explicit RAII wrapper that implements `AutoCloseable` or an explicit `dispose()` contract.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST ALWAYS pair every `StableRef.create(obj)` with an explicit `ref.dispose()` inside a `try/finally` block or within an attested terminal bridge callback.

Engineers MUST ALWAYS pair every `StableRef.create(obj)` with an explicit `ref.dispose()` inside a `try/finally` block or within an attested terminal bridge callback.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Native callbacks passing `COpaquePointer` context to Swift or C MUST unpack the pointer using `COpaquePointer.asStableRef<T>()` and explicitly call `dispose()` when the callback represents a single-shot terminal event.

Native callbacks passing `COpaquePointer` context to Swift or C MUST unpack the pointer using `COpaquePointer.asStableRef<T>()` and explicitly call `dispose()` when the callback represents a single-shot terminal event.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Code MUST NEVER cast an unverified native pointer to `COpaquePointer.asStableRef<T>()` without verifying non-nullness and thread/context validity to avoid undefined behavior and process aborts.

Code MUST NEVER cast an unverified native pointer to `COpaquePointer.asStableRef<T>()` without verifying non-nullness and thread/context validity to avoid undefined behavior and process aborts.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Kotlin Multiplatform Cinterop Native Memory Ownership & StableRef Deallocation Standard critical for AI coding assistants?

Mandates deterministic lifecycle management for native memory allocations and StableRef handles crossing Kotlin/Native and C/Objective-C/Swift boundaries. Eliminates native heap fragmentation, uncollected bridge references, and fatal SIGSEGV dangling pointer crashes by enforcing scoped arena lifecycles and explicit disposal invariants. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unbounded Native Heap Allocations and Undisposed StableRef Leaks Across FFI Boundaries) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Kotlin