Wednesday, April 1, 2020

How do C and Rust programs differs in memory safety - Example 2

memory-safety 2

Memory safety example 2

This is one of the well known problem in C programming language - Array Overflow.
C compiler really won’t care the boundary of arrays , you can even point to the value beyond array length using a pointer as if you are traversing through it.

C Program

  1 
  2 int main(){
  3 
  4     int a[3] =  {1,2,3 };
  5     char c = 'a';
  6     char d = 'b';
  //pointer to the array, 
  //usually array itself is a pointer
  // to the first address of the array 
  7     printf("array = %d " , *a );
  8     printf("array = %d " , *(a+1) );
  9     printf("array = %d " , *(a+2) );
 10     
 11     
 12     //memory overflow , we are trying to access beyond array's length
 13     //but compiling is not complaining
 14 
 15     printf("array = %d " , *(a+3) );
 16     printf("array = %d " , a[5] );
 17 
 18 }

Output is

array = 1 array = 2 array = 3 array = 0 array = 32764 

We will see how Rust program restricts this vulnerability .

Rust Program

trying to create pointer and dereferencing it below, but compiler catches it

 1 
  2 fn main() {
  3 
  4     let a = [1,2,4];
  5 
  6     let p = &a;
  7     
  8     println!("array ={:?}",*p+1);
  9 
 10 }

error is

--> src/main.rs:8:31
  |
8 |     println!("array ={:?}",*(p+1)); 
  |                              -^- {integer}
  |                              |
  |                              &[{integer}; 3]


if you try to access it through index, as a[3] , below is the error


error: this operation will panic at runtime
 --> src/main.rs:8:26
  |
8 |    println!("array = {}",a[3]);
  |                          ^^^^ index out of bounds: the len is 3 but the index is 3
  |
  = note: `#[deny(unconditional_panic)]` on by default

No comments: