Contents

Lec5-C Memory Management

C Memory Management

malloc

1
2
3
4
5
6
// with the help of a typecast and sizeof 
ptr = (int *) malloc(n * sizeof(int));
/* check if malloc was successful */
if (ptr == NULL) {
    /* handle error */
}
1
2
3
ptr = (int *) realloc(ptr, (n+1) * sizeof(int));

free(ptr); // realloc(ptr, 0)

不要踩坑!

/lec5-c-memory-management/image.png

An array name is not a variable. – K&R

when call &arr , just get the address of the first element of the array

Linked List Example

1
2
3
4
5
6
7
8
9
struct node {
    char *data;
    struct node *next;
};
typedef struct node *List; // 定义 List 为 struct node 的指针类型

List create_empty_list() {
    return NULL;
}

Memory Locations

分配内存的方式

/lec5-c-memory-management/image-1.png

三个存储池

/lec5-c-memory-management/image-2.png

栈的映像图 LIFO /lec5-c-memory-management/image-3.png

Memory Management

stack, static memory are easy to handle, but heap is a bit more complicated…

/lec5-c-memory-management/image-4.png

Implementing malloc and free

/lec5-c-memory-management/image-5.png /lec5-c-memory-management/image-6.png

When Memory Goes Bad

  • 不要轻易的访问栈区指针 / 地址

/lec5-c-memory-management/image-7.png

  • 忘记realloc会移动数据

/lec5-c-memory-management/image-8.png

  • 移动指针但是胡乱free or double free 🤯

Valgrind?

  • Valgrind is a tool for detecting memory errors in C and C++ programs.