liveBook · Manning

Undefined behavior

As explained in Refactoring to Rust

Undefined behavior is program execution whose effects are not constrained by the language or platform specification.

Undefined behavior occurs when execution effects are not constrained by the language or platform specification. At a Rust/C boundary, dereferencing a null pointer is undefined behavior, so untrusted pointers must be checked before unsafe access. section 3.2.2

Handle pointer-based FFI conservatively:

  • Check raw pointers with is_null before dereferencing them. section 3.2.2
  • Keep the actual pointer write inside an unsafe block. section 3.2.2
  • Validate both the input string pointer and output solution pointer before converting or writing through them. section 3.2.2

Protecting a C out-parameter

A Rust solve function receives a C string pointer and a solution output pointer. It returns early when solution.is_null(), then uses an unsafe block to assign 1024 through the validated pointer. Without the assignment, the C program prints an uninitialized value. section 3.2.2

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

  unsafe {
    *solution = 1024;  #2
  }

  0
}

Shows the null check, unsafe pointer write, and C-compatible solve function together. section 3.2.2

How Refactoring to Rust covers it

How deep it goes
Defines null-pointer dereference as undefined behavior and demonstrates a null check before an unsafe write, without covering broader cases.
Examples
Uses a C calculator's solution out-parameter and Rust's solve function, first producing an uninitialized result and then writing 1024.
What you can do after
Apply it via null checks and narrowly scoped unsafe blocks when writing through C-provided pointers.
How it connects
Connects unsafe Rust with raw pointers, null pointers, C FFI, and C strings.

Also explained in

Compare how 7 books explain undefined behavior →

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.