FAQ - Help and questions

How do C pointers, malloc and free map to Rust?

#porting#c-language#memorypublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Heap memory you malloc and free becomes a Vec, String or Box that frees itself. Borrowed pointers become references (&T and &mut T) or slices, nullable pointers become Option, and a pointer plus a length becomes a slice. Raw pointers exist, but only for FFI and are used inside unsafe code.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

In C one pointer type does four jobs: it owns memory, it borrows memory, it may be null, and it may point to many items. Rust has a separate type for each job, and the compiler checks the rules that C leaves to the programmer. Translate by asking which job each pointer does.

CRustNotes
T *p = malloc(sizeof *p) ... free(p)Box<T>Freed when it goes out of scope; no free
T *a = malloc(n * sizeof *a) ... free(a)Vec<T>Grows with push; knows its length
char *s (owned text)StringUTF-8, owns its bytes
const T *p (borrowed, read only)&TChecked: cannot outlive the value
T *p (borrowed, changed through)&mut TOnly one at a time
const T *a, size_t n&[T]A slice carries its length
pointer that may be NULLOption<&T>, Option<Box<T>>None is the null; same size as a pointer
T *next in a linked structure that owns its tailOption<Box<Node>>
void *a generic type parameter, or a trait object
T * across a C interface*const T, *mut TRaw pointers: using them needs unsafe

This program shows the four common rewrites. It was compiled and run with rustc 1.93.0.

src/main.rsrust
// C:  int *buf = malloc(n * sizeof *buf);  ...  free(buf);
// Rust: a Vec owns the memory and frees it when it goes out of scope.
fn sum_squares(n: usize) -> u64 {
    let mut buf: Vec<u64> = Vec::with_capacity(n);
    for i in 0..n as u64 {
        buf.push(i * i);
    }
    buf.iter().sum()
} // buf is freed here; there is no free() to forget

// C:  int *find(const int *a, size_t n, int x)  returning a pointer or NULL
// Rust: a borrowed slice in, an Option out.
fn find(a: &[i32], x: i32) -> Option<&i32> {
    a.iter().find(|&&v| v == x)
}

// C:  void bump(int *p) { *p += 1; }
// Rust: a mutable reference, checked at compile time.
fn bump(p: &mut i32) {
    *p += 1;
}

// C:  struct node { int v; struct node *next; };  (a list that owns its tail)
// Rust: Option<Box<...>> is "a pointer that may be null and owns what it points to".
struct Node {
    v: i32,
    next: Option<Box<Node>>,
}

fn len(mut at: &Option<Box<Node>>) -> usize {
    let mut n = 0;
    while let Some(node) = at {
        n += 1;
        at = &node.next;
    }
    n
}

fn main() {
    println!("{}", sum_squares(5));
    let a = [3, 5, 7];
    println!("{:?} {:?}", find(&a, 5), find(&a, 9));
    let mut x = 1;
    bump(&mut x);
    println!("{x}");
    let list = Some(Box::new(Node { v: 1, next: Some(Box::new(Node { v: 2, next: None })) }));
    println!("{} {}", len(&list), list.as_ref().map(|n| n.v).unwrap_or(0));
}
text
30
Some(5) None
2
2 1

Common mistakes#

  • Translating every T * to a raw pointer and wrapping the code in unsafe. That keeps C's problems; use the safe type that matches the job.
  • Porting pointer arithmetic literally. Iterate over a slice (for x in &a) or use indices, which are bounds-checked.
  • Porting a doubly linked list or a graph directly. Owned back-pointers do not fit Rust's rules; use indices into a Vec, or Rc/Weak when sharing is real.

What replaces NULL checks?#

Option. The compiler will not let you use the value without handling None, so a missing check is a compile error instead of a crash.

What happens to pointer-and-length pairs?#

They become slices. A &[T] is a pointer and a length in one value, and indexing past the end stops the program with a clear panic instead of reading memory it does not own.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet