Gdb Introduction



  • Gdb Introduction

    What is gdb?

    • "GNU Debugger"
    • A debugger for several laguages, include C and C++

    Basic Usage

    If you want to use gdb, you need to add -g option when you use gcc to compile your program.
    Gdb has an interactive shell, so it also has some features like the ordinary shell such as recall history with arrow keys and auto-complete words wit TAB.

    Start gdb

    you can start it directly

    gdb ./xxx //program name
    

    or you can start gdb first

    gdb
    (gdb) file xxx
    
    Basic Commands

    Here is some basic commands in gdb, and you can use the whole name or the abbreviation in the parenthese.

    //run the program
    (gdb) run(r)
    //set breakpoints
    (gdb) break(b) file.c:6//set with line number
    (gdb) break(b) my_func//set with function name
    //continue the program, run will resatrt from the beginning
    (gdb) continue(c)
    //run step by step, will step into a func if next line is a func
    (gdb) step(s)
    //run step by step, won't step into a func if next line is a func
    (gdb) next(n)
    //print value
    (gdb) print(p) my_var
    (gdb) print(p)/x my_var
    //watch a value, it will stop when  is modified
    (gdb) watch(w) my_var
    //produce a stack trace of function calls
    (gdb) backtrace(bt)
    
    Deal with segmentation fault

    As we all know, it is quite normal for you to meet a seg fault problem. With gdb, you can detect the problem more eaisly.

    //let the core dump
    ulimit -c unlimited
    //start gdb with the core
    gdb ./xxx core
    //produce the stack trace
    (gdb)bt
    

    Tips & Skills

    Play With Pointers

    Multi Thread

    Change to another thread

    Sometimes we may find that our program stuck in an infinite loop. And if you have a moniter thread, you can use gdb to find the loop easily. You can set a breakpoint in your monitor thread, and when it stops, you can check other thread.

    (gdb) info thread //check all thread
    (gdb) thread id //change thread into another one with id
    

    Also, it is useful anytime you want to break and check the status of other thread.

    Lock other threads

    On the other hand, you just want to continue one thread, and you can also lock other thread using this:

    (gdb)set scheduler-locking on //only this thread will run
    
    (gdb)set scheduler-locking step //optimize only when run step by step
    

    You can unlock

    (gdb)set scheduler-locking off
    

    Useful Breakpoints



  • 正好需要,收藏了!



  • 想起了拆炸弹



  • 太强了,收藏了~



  • 昨天用gdb解决了一个bug,多谢阴队


  • 项目组组长

    多线程多进程调试好厉害



  • gdb 的coredump 定位段错误简直不要太好用



  • 收藏了~好好学习一下



  • 这个必须好好学学


 

Copyright © 2018 bbs.dian.org.cn All rights reserved.

与 Dian 的连接断开,我们正在尝试重连,请耐心等待