No Overruns in Rust

I love the idea of C and C++, but I hate C and C++. They’re fast and give me an immense amount of control, and they break all the time (which is ultimately my fault, I suppose). Given this, you can imagine how happy I was when I discovered Rust, a language with all the control of C++ but with a new set of compile-time static analysis on top that guarantees memory safety. There have been many talks and blog posts about how Rust catches many things at compile time, which is great, but the best feature I’ve found so far is the runtime safety.

Rust code will never segfault. Rust code will never have a buffer overrun. For example, this program in C will give you a bad time:

#include <stdio.h>
void main() {
    int array[5] = {0,1,2,3,4};
    int index = 0;
    while(1) {
        index++;
        printf("%d\n", array[index]);
    }
}

Precisely, it will read data from somewhere in memory that it shouldn’t (i.e., places after array[4]) until it eventually segfaults:

    
1
2
3
4
32764
0
7
4195648
0
0
0
0
-2028824358
-1114669975
4195312
0

[many hundreds of lines ommitted]

1634165090
6578531
1414087749
1983730255
771779945
1634890799
6514803
0
0
[1]    15046 segmentation fault (core dumped)  ./trashc

Running this through the line counter reveals that it produces about 1000 lines of output, which means it’s basically dumping the entire contents of its process and some random surrounding memory. This could easily be a very bad security problem.

In Rust, the equivalent program might be:

fn main() {
    let array: [i64; 5] = [0, 1, 2, 3, 4];
    let mut index = 0;
    loop {
        index += 1;
        println!("{}", array[index]);
    }
}

This results in a much better outcome:

1
2
3
4
thread '<main>' panicked at 'index out of bounds: the len is 5 but the index is 5', trashrust.rs:6
note: Run with `RUST_BACKTRACE=1` for a backtrace.

No security problem, and it’s far, far clearer what went wrong.

In addition to Rust’s many, many static analysis benefits, it has better runtime safety than C and completely eliminates several classes of security problems right off the bat.

*****
Written by Leo Tindall on 28 April 2016