1 Multi-threads
debug modle 下build項目應該使用-g參數:
g++ -g sample.cpp -o sample
兩種方式去進入gdb調試:
- Start the debugging with exectuable name i.e
(shell) gdb Sample
2)Start gdb alone i.e
gdb
(gdb) file Sample
通過命令行參數去傳遞參數到debug下run:
Reading symbols from Sample...done
(gdb) run 1 2 3
gdb 可以和shell終端進行交互,可以執行shell命令,使用help命令獲得幫助:
(git) help
退出時使用"quit" 命令就好:
quit
添加行斷點的方式:
(gdb) br Sample.cpp:18
(gdb) break Sample.cpp:18
(gdb) b Sample.cpp:18
so,“b”,“br”,“break” all are same.
添加函數斷點:
For global functions,
(gdb) br func
For member functions,
(gdb) br Dummy::Func
現在如果你在未run之前設置好了斷點,只需要(gdb) run
就可以開始啓動,如果已經開始了run,那麼在加入斷點之後按下"c"繼續執行(gdb) c
。
使用gdb獲取堆棧上的信息:
(gdb) bt
(gdb) f 2
Traversal When breakpoint is hit:
- n – Runs the next line in step over mode i.e. will not go inside any function just run the next line in currrnt function.
(gdb) n
- s – Runs the next line step in model i.e. if next line is a function call then it will go inside that function.
(gdb) s
To list out all breakponits use command,
(gdb) info break
To delete a breakponit use command,
(gdb) d n
條件斷點:
(gdb) sample.cpp : 8 if val==8
多線程調試(Compiling Mutli-threaded Code using g++ with Debug Info):
To compile code in debug model in gcc/g++ we need to use option “-g”
Also in linux to compile multi threading we need to include pthread library option i.e. “-pthread”
g++ -g -std=c++11 -pthread smaple.cpp -o sample
List all the activate threads use command:
(gdb) info threads
每行包括包含一個活動線程的id,和幀信息,第一列是一個指定的id。
單線程時(only have main function):
(gdb) bt
多線程(Mutli-threads) 使用上述,only show current activate thread:
(gdb) thread apply all bt
Switch between threads while debugging:
(gdb) thread <Thread number>
將gdb與正在鏈接的進程連接起來:
ps -elf | process <NAME>
(gdb) sample <pid>
2 core dunp
core dump又叫核心轉儲, 當程序運行過程中發生異常, 程序異常退出時, 由操作系統把程序當前的內存狀況存儲在一個core文件中, 叫core dump. (linux中如果內存越界會收到SIGSEGV信號,然後就會core dump)
造成segment fault,產生core dump的可能原因
-
1 內存訪問越界
-
- a) 由於使用錯誤的下標,導致數組訪問越界
-
- b) 搜索字符串時,依靠字符串結束符來判斷字符串是否結束,但是字符串沒有正常的使用結束符
-
- c) 使用strcpy, strcat, sprintf, strcmp, strcasecmp等字符串操作函數,將目標字符串讀/寫爆。應該使用strncpy, strlcpy, strncat, strlcat, snprintf, strncmp, strncasecmp等函數防止讀寫越界。
-
2 多線程程序使用了線程不安全的函數。
-
3 多線程讀寫的數據未加鎖保護。對於會被多個線程同時訪問的全局數據,應該注意加鎖保護,否則很容易造成core dump
-
4 非法指針
-
- a) 使用空指針
-
- b) 隨意使用指針轉換。一個指向一段內存的指針,除非確定這段內存原先就分配爲某種結構或類型,或者這種結構或類型的數組,否則不要將它轉換爲這種結構或類型的指針,而應該將這段內存拷貝到一個這種結構或類型中,再訪問這個結構或類型。這是因爲如果這段內存的開始地址不是按照這種結構或類型對齊的,那麼訪問它時就很容易因爲bus error而core dump.
-
5 堆棧溢出.不要使用大的局部變量(因爲局部變量都分配在棧上),這樣容易造成堆棧溢出,破壞系統的棧和堆結構,導致出現莫名其妙的錯誤。
-
6 系統配置,首先使用
ulimit -c
查看core file大小配置,如爲0,則表示系統未開啓dump core。可以用ulimit -c unlimited
開啓core dump.
使用gdb查看core文件:
發生core dump之後, 用gdb進行查看core文件的內容, 以定位文件中引發core dump的行.
gdb [exec file] [core file]