debug_flow
- Debugging tips from the book "The Practice of Programming":
- Look for familiar patterns.
- Examine the most recent change.
- Don't make the same mistake twice.
- Debug it now, not later.
- Get a stack trace.
- Read before typing.
- Explain your code to someone else.
- Make the bug reproducible.
- Divide and conquer.
- Study the numerology of failures.
- Display output to localize your search.
- Write self-checking code.
- Write a log file.
- Draw a picture.
- Use tools.
- Keep records.
先刻意 遮住 自己對程式的知識,從觀察到的行為開始推理:
1. 由 Segmentation fault 可知程式因 非法記憶體存取 而結束,即試著讀或寫某記憶體位置,而該位置被設定成不能那樣存取。 先找出此記憶體存取動作 ,最快方法是得到 stack trace 。
2. stack trace 內含每一層的函式呼叫以及在函式中執行到那一行,可看出當在哪裡。取得方法見:https://docs.google.com/document/d/13XVxoMlJ9kLXNvZcE16ThJcOKoMg3jFeGZ62RgxuBwg/edit 中 "從 core dump 得到 stack trace"。要找到出錯的記憶體存取是讀還是寫,作用在哪筆資料上。
3. 接著分析記憶體存取 動作 跟 位置 的組合。記憶體位置可分類為:a. stack b. 從可執行檔 data section 配置的,分可讀寫與唯讀 c. heap: 執行期間透過 malloc(), mmap() 配置的。
從第三步要往後繼續推理你可能缺一些背景知識,會沒有把握。但接受程式當掉是事實,由此開始 逆向推理 ,以及學會工具操作得到 stack trace 是關鍵。
『C 程式除錯入門』在我們高中社團每屆都教,見柏崴錄的動畫: http://www.itrs.tw/teaching_shows/stacktrace.html
page revision: 3, last edited: 21 Jun 2012 01:00