# 笔记

#### 0.上节课的练习的答案

```#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只是比其他语言犯错更难一些，并不代表不可以犯错。而且很多逻辑错误是无关语言的。

## 资源：

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