gdb学习1:初识gdb
原创
©著作权归作者所有:来自51CTO博客作者wx631a9cd48516d的原创作品,请联系作者获取转载授权,否则将追究法律责任
(为了看起来比较舒服,罗里吧嗦的东西,我就不往上面粘贴了,以后都是这样,不再解释)
gdb是linux上的调试工具,功能非常强大,我这里是debian9.8,默认是没有安装gdb的,所以要先安装:
gyz@debian:~/mc$ sudo apt-get install gdb
先写个程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *MyStrCopy(const char *s1)
{
if(NULL == s1)
{
return "string is NULL";
}
else
{
/*
char *s2 = (char *)malloc(strlen(s1)+1);
if(NULL == s2)
{
return "malloc error";
}*/
char *s2 = NULL;
char *p = s2;
while((*s2++ = *s1++));
return p;
}
}
int main(int argv,char **argc)
{
const char *str1 = NULL;
const char *str2 = "string copying";
printf("%s\n",MyStrCopy(str1));
printf("%s\n",MyStrCopy(str2));
return 0;
}
编译执行:
gyz@debian:~/mc$ gcc strcopy.c -o strcopy -Wall
gyz@debian:~/mc$ ./strcopy
string is NULL
段错误
结果出现了很有名的“段错误”,就是内存非法访问了,这个不是编译阶段,没有办法知道具体哪里有错,当然了,我们可以用printf()函数去打印可能有错误的地方,但是如果存在错误的地方很多的话,会写很多printf()函数,调试结束,还要删除,显得好麻烦,那gdb的强大之处就来了。如下,一下子就知道了哪里有错了,是不是很强大。
gyz@debian:~/mc$ gcc strcopy.c -o strcopy -Wall -g
gyz@debian:~/mc$ gdb
(gdb) file strcopy
Reading symbols from strcopy...done.
(gdb) r strcopy
Starting program: /home/gyz/mc/strcopy strcopy
string is NULL
Program received signal SIGSEGV, Segmentation fault.
0x00005555555546f4 in MyStrCopy (s1=0x5555555547f4 "tring copying")
at strcopy.c:21
21 while((*s2++ = *s1++));
(gdb)
(gdb) q
A debugging session is active.
Inferior 1 [process 3499] will be killed.
Quit anyway? (y or n) y
gyz@debian:~/mc$
解释:
1,编译时,需要加入-g选项;
2,file 打开可执行文件,也可以用exec-file打开;
3,r就是run,就是运行可执行文件;
4,最后提示在21出现了段错误;
5,q是quit,就是放弃的意思,最后输入y是因为哥哥程序还没有结束;
6,另外的一种gdb的调试方法,将在下篇博文(另一种打开可执行文件的方法)里说明。