程序写好了,编译好了。可是一运行就出现段错误,怎么办呢?用调试啊
linux中调试工具是gdb,不是gdp
1.1.1.gdb常用命令
Linux 包含了一个叫gdb的调试程序。gdb可以用来调试C和C++ 程序。
在程序编译时用 -g 选项可打开调试选项.
按 Tab 键补齐命令,用光标键上下翻动历史命令. 用help up看帮助
1.2. gdb 应用举例
下面列出了将被调试的程序它显示一个简单的问候, 再用反序将它列出
main.cpp:
void MyPrint(const char *pszSrc);
void MyPrint2(const char *pszSrc);
int main ()
{
char szSrc[]= "hello there";
MyPrint(szSrc);
MyPrint2(szSrc);
}
func.cpp
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void MyPrint(const char *pszSrc)
printf("The string is %s\n", pszSrc);
}
void MyPrint2(const char *pszSrc)
{
char*pszRev;
int i,iLen;
iLen=strlen(pszSrc);
pszRev=(char*)malloc(iLen+1);
for(i=0;i<iLen;i++)
pszRev[iLen-i]=pszSrc[i];
pszRev[iLen]='\0';
printf("The revert string is:%s\n",pszRev);
free(pszRev);
}
用下面的命令编译它(注意加上-g的编译选项):
g++ -g *.cpp
(gdb) file a.out
(gdb) run
(gdb) l[ist] func.cpp:1 列出源代码: 技巧: 在gdb 提示符下按回车健将重复上一个命令.
(gdb) break 17
(gdb) run
(gdb) watch pszRev[iLen-i]
(gdb) n
(gdb) info b [查看所有断点信息]
(gdb) d b
(gdb) b 17 if i>=iLen-1 [只有在i>=iLen-1时才停止在17行]
(gdb) continue [继续全速运行]
(gdb) p i
(gdb) p iLen
练习:
1.用gdb调试下面程序(程序想倒序输出str的内容)
#include <stdio.h>
int f1(char *str);
int f2(char *str);
int main()
{
char str[]="helloworld";
f1(str);
f2(str);
return 0;
}
int f1(char *str)
{
printf("f1 str is%s",str);
}
int f2(char *str)
{
char *str2;
int size, i;
size=strlen(str);
str2=(char*)malloc(size+1);
for(int i=0; i<size; i++)
str2[size - i] = str[i];
str2[size+1]='\0';
printf("f2 str is%s",str2);
}
步骤:
gcc –g –o str.out str.c
gdb str.out
gdb>l
gdb>b 30 for处设断点
gdb>b 33 printf处设断点
gdb>info b
gdb>r
gdb>n
gdb>p str2[size-i] 多次运行看值对不
gdb>c
gbd>p str2[0] 看str2数组中的值