1.有时候IDE不好用时,比如占用内存大,启动慢,或Debug不了时,开启IDE调试会反映很慢。
2.这时借助gdb命令行调试能快速定位问题。
3.特别是服务器端开发时也需要从命令行调试。
//一段有问题,并且会崩溃的代码~~
#include <stdio.h>
typedef struct WordObject WordObject;
struct WordObject
{
char* path;
int num;
};
WordObject* Test()
{
char* path = "wolegequ";
int number = 1;
WordObject obj;
obj.num = number;
obj.path = path;
return &obj;
}
int main()
{
WordObject* oo = Test();
oo = NULL;
printf("%s\n", oo->path);
return 0;
}
调试命令:
E:\workspace\workspace_c++\read_config\src\read_config>gdb read_config_info
GNU gdb (GDB) 7.2
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "mingw32".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from E:\workspace\workspace_c++\read_config\src\read_config/read
_config_info.exe...done.
(gdb) l //从第一行开始例出原码
707
708 WordObject obj;
709 obj.num = number;
710 obj.path = path;
711
712 return &obj;
713 }
714
715 int main()
716 {
(gdb) break Test //设置断点函数
Breakpoint 1 at 0x4013c6: file read_config_info.cpp, line 705.
(gdb) break 708
Breakpoint 2 at 0x4013d4: file read_config_info.cpp, line 708. //设置断点行号位置
(gdb) r //运行程序
Starting program: E:\workspace\workspace_c++\read_config\src\read_config/read_co
nfig_info.exe
[New Thread 5040.0x650]
Breakpoint 1, Test () at read_config_info.cpp:705
705 char* path = "wolegequ";
(gdb) c //继续执行
Continuing.
Breakpoint 2, Test () at read_config_info.cpp:709
709 obj.num = number;
(gdb) n //单步执行
710 obj.path = path;
(gdb) n
712 return &obj;
(gdb) p path //查看变量值
$1 = 0x403064 "wolegequ"
(gdb) p obj.num //查看对象中的值
$2 = 1
(gdb) bt //查看堆栈信息
#0 Test () at read_config_info.cpp:712
#1 0x004013f8 in main () at read_config_info.cpp:717
(gdb) break 718
Breakpoint 3 at 0x4013fc: file read_config_info.cpp, line 718.
(gdb) c
Continuing.
Breakpoint 3, main () at read_config_info.cpp:718
718 oo = NULL;
(gdb) bt
#0 main () at read_config_info.cpp:718
(gdb) n
719 printf("%s\n", oo->path);
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0x00401408 in main () at read_config_info.cpp:719
719 printf("%s\n", oo->path);
(gdb) bt //程序崩溃前查看堆栈信息
#0 0x00401408 in main () at read_config_info.cpp:719
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0x00401408 in main () at read_config_info.cpp:719
719 printf("%s\n", oo->path);
(gdb) n
Program exited with code 030000000005. //退出
(gdb) q