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






