021 abnormal security of rust Necromancer’s book



The videos recorded in this series are mainly put on station BRust dead book learning video

The source code information related to rust dead book is ingithub.com/anonymousGiga/Rustonomi…

Abnormal security

Two levels of exception security are mainly considered in rust:

  • In non secure code, the lower limit of exception security is to ensure that memory security is not violated, which is called minimum exception security;
  • In secure code, exception security ensures that the program is doing the right thing at all times. We call it maximum exception security.

Most non secure code is easier to implement exception security because it controls every detail of program operation, and most of the code does not panic. However, special attention should be paid to operations such as repeatedly running external code on an initialized array. For example, the following code:

//Vec::push_ All simplified implementation example to illustrate the situation
impl<T: Clone> Vec<T> {
    fn push_all(&mut self, to_push: &[T]) {
        unsafe {
            //Because we called reserve, there will be no overflow
            self.set_len(self.len() + to_push.len());

            for (i, x) in to_push.iter().enumerate() {
                self.ptr().offset(i as isize).write(x.clone());

explain: however, if panic occurs when calling clone, the allocated memory will not be initialized. When VEC is accessed or destroyed, the uninitialized memory will be read.

terms of settlement
The problem with the above program is to set the length first and then initialize. The solution is to set the length after initialization.

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Linghu rushed