Rust如何在C/C++中进行数组操作

laokugonggao
发布于 2020-9-3 18:08
浏览
0收藏

Rust的第一个稳定版本于2015年发布。与1980年代左右诞生的C / C ++相比,它是后起之秀。

作为系统级编程语言,Rust的设计标准是安全性,速度和并发性。 当然,C / C ++可能对此并不赞同!

 

那么当 Rust 遇上 C/C++ 会在哪些方面进行讨论呢?我们先从数组操作谈起。

环境:Cent OS 8(Kernel 4.18.0),gcc 8.3.1,g++ 8.3.1,rustc 1.43.1。

 

c

#include <stdio.h>

int main() {
  int a[] = {1, 2, 3, 4, 5};
  int index = 10;

  int element = a[index];

  printf("The value of element is: %d\n", element);

  return 0;
}
$ gcc main.c
$ ./a.out
The value of element is: -721516429

编译没有产生任何错误,程序正常运行,“成功”访问了无效的内存 a[10]。

 

C++

#include <iostream>

using namespace std;

int main() {
  int a[] = {1, 2, 3, 4, 5};
  int index = 10;

  int element = a[index];

  cout << "The value of element is: " << element << endl;

  return 0;
}
$ g++ main.cc
$ ./a.out
The value of element is: 1914456179

同样,编译没有产生任何错误,程序正常运行并访问了无效的内存 a[10]。

 

Rust
 

fn main() {
  let a = [1, 2, 3, 4, 5];
  let index = 10;

  let element = a[index];

  println!("The value of element is: {}", element);
}
$ rustc main.rs
$ ./main
thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 10', main.rs:5:19
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

编译没有产生任何错误,但程序导致运行时错误并没有成功退出。

 

当我们尝试使用索引访问一个元素时,Rust 将检查您指定的索引是否小于数组长度。如果索引大于或等于数组长度,Rust 将陷入 Panic。

总结
当提供不正确的索引时,C/C++ 可以访问无效的内存。

 

Rust通过立即退出而不是允许内存访问,从而避免这种错误。大家是否觉得这样更安全呢?

Rust 由于提供了额外安全保证,可能会降低一些性能。

哪有什么岁月静好,都是有人替你负重前行!

当然,如果 C/C++ 的使用者足够细心,自己能提供安全保证的话,是同样可以避免错误的。

标签
已于2020-9-3 18:08:22修改
1
收藏
回复
举报
回复