现在的位置: 首页 > 综合 > 正文

gdb命令和使用示例

2013年09月14日 ⁄ 综合 ⁄ 共 1241字 ⁄ 字号 评论关闭

 

原文链接:http://www.javaarch.net/jiagoushi/799.htm

 

gdb命令和使用示例

	b main - 在main函数开始处设置断点
	b - 在当前行设置断点
	b N - 在第N行设置断点
	b +N - 在当前行后第N行设置断点
	b fn - 在函数fn出设置断点
	d N - 删除第N个断点
	info break - 查看所有断点
	r - 继续执行,直到有异常或者退出
	c - c继续到下一个断点
	f - 执行直到当前函数结束
	s - 单步执行
	s N - 执行下面N行
	n - 单步跳过执行
	u N - 执行到当前行所在的前N行处
	p var - 打印当前变量var的值
	bt - 打印当前堆栈信息
	u - 执行到当前堆栈的上一个
	d - 执行到当前堆栈的下一个
	q - 退出gdb
	
示例:

	 #include <iostream> 
	  using namespace std;
	  void setint(int*, int);
	  int main() {
		int a;
		setint(&a, 10);
		cout << a << endl;
		int* b;
		setint(b, 10);
		cout << *b << endl;
		return 0;
	  }
	  void setint(int* ip, int i) {
		*ip = i;
	  } 
编译:

    $g++ -g crash.cc -o crash
   
执行:

    segmentation fault (core dumped) 
	
使用gdb调试这个error

	$ gdb crash
		(gdb) r
		Starting program: /home/tmp/crash
		10
		10
		Program received signal SIGSEGV, Segmentation fault.
		0x4000b4d9 in _dl_fini () from /lib/ld-linux.so.2
		(gdb) where
		#0  0x4000b4d9 in _dl_fini () from /lib/ld-linux.so.2
		#1  0x40132a12 in exit () from /lib/libc.so.6
		#2  0x4011cdc6 in __libc_start_main () from /lib/libc.so.6
		#3  0x080485f1 in _start ()
		(gdb) 
		
		(gdb) b main
		# Set a breakpoint at the beginning of the function main
		(gdb) r
		# Run the program, but break immediately due to the breakpoint.
		(gdb) n
		# n = next, runs one line of the program
		(gdb) n
		(gdb) s
		setint(int*, int) (ip=0x400143e0, i=10) at crash2.C:20
		# s = step, is like next, but it will step into functions.
		# In this case the function stepped into is setint.
		(gdb) p ip
		$3 = (int *) 0x400143e0
		(gdb) p *ip
		1073827128 
		
这里ip的指针没有初始化,所以指向内存位置是随机的,这里会导致core dump。

 

抱歉!评论已关闭.