从零开始的 Rust 学习笔记(7)——Lifetime

这次的笔记只讲一个东西——Lifetime☆〜(ゝ。∂)

倒也不是说特别复杂,不过算是很与众不同的一个 feature~Rust的内存安全、无需 GC(垃圾回收) 则是因为有这个 feature(当然,真要在运行时搞事情的话,,编译器静态分析也未必能保证 100% 的安全)

然后我们说的内存安全的话,则是指需要禁止以下两种情况发生

  1. Use After Free
  2. Dangling Pointer

第一种情况的话,可能会导致 Segment Fault,也有可能会被 Hacker 利用,例如有些 iOS 版本上的越狱的一部分,则是基于 kernel 中包含了 UAF 的代码,UAF 的地址上的内容又可以被用户控制,随后通过一系列操作,在 kenrel 某些可以提权的代码里,再次 allocated 并用到这块被用户控制的内存时,就可以实现原本 需要 privileged 的操作了~

对于第二种情况的话,也就是「野指针」,比如某个函数返回了其栈上的内存的指针,而我们知道,当函数返回时,其栈上的内容是会被销毁的( ;´Д`)

举例如下~看看最后的输出是什么

#include <stdio.h>

int * stack_ref() {
    // local variable `ret` is located on stack
    int ret = 233;
    // return address of stack memory associated with local variable `ret`
    return &ret;
}   // at this point, the stack memory is no longer valid

int main(int argc, char *argv[]) {
    // get a ref, but on stack
    int * ref = stack_ref();
    // inc 4
    *ref += 4;
    
    // call that again
    stack_ref();
    
    // and please guess the value
    printf("Guess: %d\n", *ref);
}
Continue reading 从零开始的 Rust 学习笔记(7)——Lifetime