DAY 12
0

## Days 12: 垃圾回收器系列：概念、粗略實現

### ▌閱讀本文章的垃圾回收器系列前：

Days 3: 重溫指標：記憶體地址 、 儲存空間
Days 7: 重溫指標：數據、數據類型的本質

Days 8: 重溫指標：雜項：指標宣告、運算符 是基礎知識及雜項，不看不影響本系列閱讀。

Days 9: 動態記憶體分配：malloc()、calloc()、realloc()、free()，內存洩露

Days 10: atexit()、函數程序結束時調用函數

Days 11: 什麼是垃圾回收器？

#### ▌垃圾回收器的粗略實現：

``````int *ptr = (int*)malloc(10 * sizeof(int));
free(ptr);
``````

``````int *ptr = (int*)malloc(10 * sizeof(int));
``````

``````atexit();
``````

#### ▌欸？？！

``````int *ptr = (int*)malloc(10 * sizeof(int));
atexit(free(ptr));
``````

#### ▌所以肯定有一個這樣的函數存在：

``````void a_function_for_atexit_to_register(void){
//somethings to free()
}
``````

``````void a_function_for_register_address(void *address){
}
``````

``````void *my_malloc(int size);
void my_malloc(void **ptr, int size, int type_side);
``````

#### ▌粗略估計 my_malloc() 的實現：

``````void my_malloc(void **ptr, int size, int type_side){
/*分配記憶體*/
*ptr = malloc(size * type_side);

/*紀錄地址*/

/*註冊 atexit() */
/*僅在程序第一次執行時呼叫 atexit() */
static int first_process = 1;
if (first_process) {
atexit(&a_function_for_atexit_to_register);  //此函數只會被呼叫一次
first_process = 0;  //第一次執行的標記
}
}
``````

#### ▌小結

``````void a_function_for_atexit_to_register(void);
void my_malloc(void **ptr, int size, int type_side);
``````

``````void free_all_register_address(void);
void new_1d(void **ptr, int length, int type_side);
``````