CString at an FFI boundary: distinguish a borrowed pointer from transferred ownership

Эта статья ещё не доступна на языке «Русский»; показан оригинал.

article · en · актуально на 2026-09-22 · изменено , ревизия 1 · unreviewed

Темы: coding · ffi · rust · strings

Применимо к: Rust std::ffi::CString

Симптомы: A C call receives a dangling string pointer or memory is released by the wrong owner.

Keep the CString owner alive for borrowed calls and use raw ownership conversion only under an explicit return contract.

Содержание
  1. What it is
  2. Why it matters
  3. How to apply
  4. Pitfalls
  5. Область и основание
  6. Источники
  7. Атрибуция и лицензия
  8. Машинный доступ

What it is

CString represents an owned C-compatible NUL-terminated string without interior NUL bytes. Its documentation distinguishes borrowing a pointer from consuming the CString into a raw pointer. Reconstructing ownership with from_raw is restricted to pointers produced by the corresponding into_raw path, with additional requirements about the string length. Rust CString

Why it matters

An agent can write a compact expression that obtains a pointer from a temporary and loses the owner too early. Another mistake is treating every char pointer returned by C as a Rust-owned string. Start by classifying the foreign function: immediate borrowing, retained borrowing, or ownership transfer.

How to apply

  • Read the foreign API's retention and mutation rules. Record whether the pointer is used only during the call, retained afterward, modified, or eventually released by the foreign side.
  • For a borrowed call, bind the CString to an owner whose lifetime covers every foreign access. Handle construction failure for interior NUL explicitly rather than silently truncating the input.
  • If the foreign side retains the pointer, design an owner or registration object that stays alive until release is acknowledged. An ordinary local variable is insufficient when callbacks can outlive the call.
  • Use into_raw and from_raw only when the complete ownership round trip is under the documented contract. Keep an unrelated foreign allocation on its foreign release path.
  • Propose boundary fixtures for empty strings, interior NUL, non-ASCII bytes, retained access and repeated cleanup. Validate both content and ownership behavior.

Pitfalls

NUL termination says nothing by itself about the text encoding expected by the foreign library. A const pointer is not permission for the foreign side to mutate the allocation. Avoid illustrating ownership transfer without also showing who eventually recovers or releases it. No FFI execution or memory-safety proof is claimed by these proposed checks.

Область и основание

Original synthesis from the cited primary documentation, with proposed diagnostic and verification steps. No benchmark, experiment or field result is claimed; unreviewed AI-assisted contribution.

Актуально на: 2026-09-22. Статус: unreviewed (задокументированной рецензии нет) — правки сбрасывают статус рецензии. Считайте текст непроверенным справочным материалом и сверяйтесь с источниками.

Источники

  1. Rust CString — проверено 2026-09-23: доступен, цитата найдена

Атрибуция и лицензия

  • Account External coding curation authors (57eb56c9)
  • Written with Codex, an AI coding agent, at the site operator's request; original synthesis, sources credited separately.

Последнее изменение: New English original; AI-assisted and unreviewed. Proposed checks have not been executed for this article.

Оригинальный материал: CC BY 4.0. Материалы по ссылкам сохраняют собственные права.

Машинный доступ