liveBook · Manning

Null termination

As explained in Refactoring to Rust

A C string is a contiguous character sequence terminated by a null character.

A C string is a contiguous sequence of platform-specific character types ending with a null character. Rust can borrow this memory instead of allocating a second string. section 3.2.2

When reading a null-terminated string from C:

  • Use CStr to represent the borrowed C string without taking ownership of C-managed memory. section 3.2.2
  • Convert it to a Rust string slice with to_str, which validates UTF-8 and reports invalid input. section 3.2.2
  • Keep the conversion read-only when the Rust code only needs to inspect the C buffer. section 3.2.2

Borrowing a C input line

A C function passes line as *const c_char. Rust checks for a null pointer, constructs CStr::from_ptr(line) inside unsafe code, and converts it with c_str.to_str(). The resulting slice points at the same address as the original C buffer. section 3.2.2

use libc::{c_char, c_int};
use std::ffi::CStr;

#[no_mangle]
pub extern "C" fn solve(
    line: *const c_char, solution: *mut c_int) -> c_int {
  if line.is_null() || solution.is_null() {
    return 1;
  }

  let c_str = unsafe { CStr::from_ptr(line) };  #1
  let r_str = match c_str.to_str() {  #2
    Ok(s) => s,
    Err(e) => {
      eprintln!("UTF-8 Error: {}", e);
      return 1;
    },
  };

  println!("line: {}", r_str);

  unsafe {
    *solution = 1024;
  }

  0
}

Inspect the complete FFI function that checks pointers, borrows a null-terminated C string, validates UTF-8, and prints the resulting slice. section 3.2.2

How Refactoring to Rust covers it

How deep it goes
Explains layout, borrowing, allocation avoidance, and UTF-8 validation, but does not develop string parsing beyond conversion.
Examples
Uses a C calculator line buffer, CStr::from_ptr, to_str, and matching pointer addresses to demonstrate shared memory.
What it assumes
Assumes basic C and Rust FFI pointers while teaching C-string layout, borrowed memory, and UTF-8 checks.
What you can do after
Apply it via CStr and to_str to read C-owned input without duplicating its allocation.
How it connects
Connects C FFI with CStr, string slices, UTF-8 validation, raw pointers, and unsafe Rust.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.