GDB使用和段错误调试技巧

来源:互联网 发布:在win7下安装ubuntu 编辑:程序博客网 时间:2024/05/22 02:25

关于gdb


  • test: debug.c
#include <stdio.h>#include <stdlib.h>#include <string.h>#define BIGNUM 1111void array(int ary[]);int main(int argc, char *argv[]){    int i[100];    /*选择性编译的时候gcc -o debug debug.c -DDEBUG*/    #ifdef DEBUG    printf("[%d]\n", __LINE__);//打印行号    #endif    array(i);    #ifdef DEBUG    printf("[%d]\n", __LINE__);    #endif    exit(1);}void array(int ary[]){    int i;    for(i=0; i<BIGNUM; i++)    {        ary[i] = i;    }}

1,编译的时候,要加上-g : gcc -o debug debug.c -g
2,使用gdb来启动待调试代码:

   gdb ./debug

3,列出待调试代码:

   l   list   l 10  (显示第10行)   l 1,30  (显示第1行到30行)

4,设置断点:

   b 10  (在程序的第10行,设置一个断点)   b 20 if i>= 5 (在程序的第20行,设置一个断点,并且只有当i>=5时才停下来)   info b (查看所设置的断点的信息)   delete N  (删除第N号断点)   disable N (禁用第N号断点)   enable N  (启用第N号断点)

5,启动待调试代码:

   run   r   r abcd 1234 (带参数)

6,查看相关的变量、栈的信息:

   print i   p i   display i  (跟踪显示变量的值)   backtrace full (查看当前进程的栈的信息)   bt full   whatis i (查看变量i的类型)

7,单步调试

   next (单步运行:将函数调用看作一步)   n   n 10   step (单步运行:会进入函数调用)   s   s 10 (运行10次)

8,继续运行代码:

   continue (让进程持续运行,直到遇到断点,或者进程退出为止)   c

9,退出gdb:

   quit

最常见的错误:非法内存访问(段错误 / segmentation fault)


该种错误的调试步骤:
1,编译: gcc -o debug debug.c -g
2,取消系统对core文件大小的限制:

   ulimit -c unlimited

3,让有段错误的代码去死,产生一个core文件

   ./debug

4,让gdb帮我们看看在哪里出错:

   gdb ./debug core

注:
gdb不一定100%地能找到错误的地方,如果找不到,还是要自己一步一步地找。我们要根源上写代码的时候就要避免出现此类错误,预防大于治疗。

1 0