课程总目录: https://github.com/xxg1413/CS110L
第二节 Memory Safety
视频:
Youtube:https://www.youtube.com/watch?v=cUrggIAPJEs&feature=youtu.be
Slides:https://reberhardt.com/cs110l/spring-2020/slides/lecture-02.pdf
课程笔记:https://reberhardt.com/cs110l/spring-2020/lecture-notes/lecture-02/
B站中字:https://www.bilibili.com/video/BV1Ra411A7kN?p=2
笔记
0.上节课的练习的答案
解释:https://stanford-cs242.github.io/f19/lectures/06-2-memory-safety
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
// There are at least 7 bugs relating to memory on this snippet.
// Find them all!
// Vec is short for "vector", a common term for a resizable array.
// For simplicity, our vector type can only hold ints.
typedef struct {
int* data; // Pointer to our array on the heap
int length; // How many elements are in our array
int capacity; // How many elements our array can hold
} Vec;
Vec* vec_new() {
Vec vec; //本地变量
vec.data = NULL;
vec.length = 0;
vec.capacity = 0;
return &vec; //悬浮指针
}
void vec_push(Vec* vec, int n) {
if (vec->length == vec->capacity) {
int new_capacity = vec->capacity * 2;
int* new_data = (int*) malloc(new_capacity);
assert(new_data != NULL);
for (int i = 0; i < vec->length; ++i) {
new_data[i] = vec->data[i];
}
vec->data = new_data; //忘记释放内存 内存泄露
vec->capacity = new_capacity;
}
vec->data[vec->length] = n; //指针的值改变了 n就改变了
++vec->length;
}
void vec_free(Vec* vec) {
free(vec);
free(vec->data);
}
void main() {
Vec* vec = vec_new();
vec_push(vec, 107);
int* n = &vec->data[0];
vec_push(vec, 110);
printf("%d\n", *n);//*n 迭代失效
free(vec->data);
vec_free(vec);// 双重释放
}
1.Rust编写bug的一些问题

Rust只是比其他语言犯错更难一些,并不代表不可以犯错。而且很多逻辑错误是无关语言的。
2.Rust编译器

3.Rust所有权

4.Rust的借用

5.生命周期

资源:
https://stanford-cs242.github.io/f19/lectures/06-2-memory-safety