--- tags: sysprog --- # [你所不知道的C語言:函式呼叫篇](https://hackmd.io/@sysprog/SJ6hRj-zg?type=view) 1. symbol : 人類可以看懂得自對應到一個記憶體位址 2. 程式通常不會直接操控記憶體,而是操控虛擬記憶體,虛擬記憶體才會再 mapping 到實體記憶體空間。 而這些虛擬記憶體的單元就稱為==MMU==,Memory Managment Unit :  3. 基本觀念 : 每個function都對應到一個記憶體上的地址 4. 通常function call都是==有來有回== <font color=#aaaaaa>( 雖然也有例外 )</font>,比如 `funcA() -> funcB()`。 那當function B執行完後,他必須想辦法回到原本的function A裡面,並接續原本中斷的地方繼續執行下去。這也就代表在離開A前往B之前,需要先將原本的一些data記錄下來,比如 : return address、argument、variable(畢竟B已經離開A的生命週期),而這些資料就會統整放在記憶體的stack裡面,稱為一個==stack frame== 6. brk、sbrk(program break) : 改變程式data在記憶體的空間。 ==malloc/free==實際上就是用sbrk做的。 7. 以下程式,當 count 為 $N$ 後會 SIGSEGV(stack overflow),但如果改成第二版,則 count 大約會在 $N/3$ 後 SIGSEGV ```clike int func() { static int count = 0; return ++count && func(); } int main() { return func(); } ``` ```clike int func(int x) { static int count = 0; int y = x; return ++count && func(x++); } int main() { return func(0); } ``` 由此可知,stack frame中會記錄 x ( parameter )、y ( local variable )、return value 7. 考慮以下兩段程式 : ```clike #include <stdlib.h> int main() { int *p = (int *) malloc(1024); free(p); free(p); return 0; } ``` ```clike #include <stdlib.h> int main() { int *p = (int *) malloc(1024); free(p); p = NULL; free(p); return 0; } ``` 第一段會碰到 double free 而 crash,第二段則不會有事,因為`free(NULL)`依 API 文件描述 : >If ptr is NULL, no operation is preformed. 所以有些人會習慣在`free(p);`後立刻接一個`p = NULL;`,確保就算寫錯也不會發生 double free 的錯誤 8. C語言的設計考量,讓其function call退化了,比如 : C 沒有 nested function 的機制。 如此設計是為了讓編譯器變得更簡單
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up