版权声明:欢迎转发,转发请标明出处 https://blog.csdn.net/weixin_39465823/article/details/88896419
比起上篇博文用file的方法,这篇博文(初识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;
}
编译运行调试:
debian:~/mc$ gcc strcopy.c -o strcopy -g -Wall
gyz@debian:~/mc$ gdb strcopy
Reading symbols from strcopy...done.
(gdb) l
14 char *s2 = (char *)malloc(strlen(s1)+1);
15 if(NULL == s2)
16 {
17 return "malloc error";
18 }*/
19 char *s2 = NULL;
20 char *p = s2;
21 while((*s2++ = *s1++));
22 return p;
23 }
(gdb) l
24 }
25
26 int main(int argv,char **argc)
27 {
28 const char *str1 = NULL;
29 const char *str2 = "string copying";
30 printf("%s\n",MyStrCopy(str1));
31 printf("%s\n",MyStrCopy(str2));
32 return 0;
33 }
(gdb) l
34
(gdb) b 31
Breakpoint 1 at 0x739: file strcopy.c, line 31.
(gdb) info break
Num Type Disp Enb Address What
1 breakpoint keep y 0x0000000000000739 in main at strcopy.c:31
(gdb) r
Starting program: /home/gyz/mc/strcopy
string is NULL
Breakpoint 1, main (argv=1, argc=0x7fffffffe228) at strcopy.c:31
31 printf("%s\n",MyStrCopy(str2));
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0x00005555555546f4 in MyStrCopy (s1=0x5555555547f4 "tring copying")
at strcopy.c:21
21 while((*s2++ = *s1++));
(gdb) c
Continuing.
Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.
(gdb) q
解释:
1,l就是list,就是将程序显示出来;
2,直接回车,是执行上一个命令;
3,b是break,断点,设置了31行为断点;
4,info break是显示设置断点的信息;
5,r解释过了,就是run运行;
6,n是next的意思,单步运行;
7,c是continue,继续执行,直接运行结束,或者到下一个断点处。