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]