Basic Debugging Technology for C/C ++ in Linux: a preliminary understanding

Source: Internet
Author: User

1. Several principles of debugging technology

Surprise principle: finding a mistake is a pleasant surprise. Do not be afraid of it, but be grateful.
Starting from scratch: the use of tests starts from scratch and does not involve boundary data for the moment. Although this may obscure some bugs, it may be able to find the most important bugs, for example, your program contains a huge loop body, and the Bug that is most easily discovered is executed in the first or second loop.
Top-down rule: Select step over rather than step into to save time.
Segmentation Fault principle: When a segment error occurs, the first thought should not be printf but Debugger, because in the Debugger, You can see which line of your code causes an error, more importantly, you can get more useful information through tools such as backtrace.
Half-fold search criteria: when looking for bugs, you can make full use of the editor and other tools for half-fold search. For details, see the following examples.
2. Code debugging tools in Linux

The main use of GDB, as well as GDB-based graphical tools, such as DDD or eclipse, depends on your personal habits.

Command-line GDB can be started quickly and can be used in an ssh terminal. The operations are simple and will not crash when debugging GUI programs, however, compared with graphics, it is inconvenient to debug or set breakpoints in a single step.

Of course, you can use Vim and other editor plug-ins or patches (clewn or vimGDB) to make up for this defect, in GDB6.1 or later versions, you can use the GDB-tui mode (or press CTRL-x-a in the command line mode of GDB) to open a text interface mode similar to the graphic interface, in this interface you can use the up and down keys to view the source code (CTRL-P and CTRL-N to view the entered command ).

Alternatively, you can use the cGDB tool (fortunately, this project was stopped for three years and someone started to maintain it again), which wraps GDB with curses, provides some useful feature (switch the Esc and I keys between the code and command boxes; Support vim-type operations in the code box; Support the tab key completion command in the Command box; when you move the row to which you want to add a breakpoint (the row number is highlighted in white), use the space key. After the settings, the row number turns red ;). In addition, eclipse is recommended when debugging C-S programs.

In this article, we will focus on the operations of ddd, because this tool combines the operations of GDB command lines and graphical interfaces. For more information, see the manual of each tool.

3. GDB command line basic operations

Program startup:
A. Cold Start
Gdb program e.g., gdb./cs
Gdb-p pid e.g., gdb-p 'pidof cs'
Gdb program core e.g., gdb./cs core. xxx
B. Hot Start
(Gdb) attach pid e.g., (gdb) attach 2313
C. input command line parameters
Gdb program -- args arglist
(Gdb) set args arglist
(Gdb) run arglist
Use shell command: shell command
Make: make-args (= shell make Make-args)
Set breakpoint: B LineNumber
Run the program: r args1 args2...
Terminate the program permanently: kill
One-step execution: n (TIPs1: you can press enter to repeat the previous operation. This feature is useful for single-step debugging ).
Single Step-in: s
Continue execution: c
Set a temporary breakpoint: tb LineNumber can be understood as a one-time breakpoint. Unlike a breakpoint, a temporary breakpoint only takes effect during the first execution.
View variable: p
Set observation points:
W Expression: When Expression is a variable name, the variable will stop executing when it changes. You can also use conditions, such as w (z> 28). When z is greater than 28, the program stops. Note that the observation points generally use variables in a larger range, rather than local variables, because the observation points set on the local variables are at the local end (for example, when the function of the variable is executed) it is canceled.
Of course, this does not include the case of main, because the program ends after the main function is executed.
View stack frames:
Stack frame refers to the place where the running information of a function call (including local variables, parameters, and the location where the function is called) is stored during a function call. Every time a function is called, a new frame is pushed into a frame maintained by the system. At the top of the stack, information about the currently running function is displayed, when the function call ends, it is displayed and analyzed.
In GDB, frame 0 is the current frame, frame 1 is the parent frame of the current frame, and frame 2 is the parent frame of the parent frame. The down command is reverse. This is a very useful information, because the information in some early frames may give you some tips.
Backtrace (bt/where) to view the entire frame Stack
Note: back and forth in the frame does not affect program execution.
Example: insert Sorting Algorithm debugging

Use pseudocode to describe the process as follows:

 

The code to be debugged is as follows:

//

// Insertion sort,

//

// Usage: insert_sort num1 num2 num3..., where the numi are the numbers

// Be sorted

Int x [10], // input array

Y [10], // workspace array

Num_inputs, // length of input array

Num_y = 0; // current number of elements in y

Void get_args (int ac, char ** av)

{Int I;

Num_inputs = ac-1;

For (I = 0; I <num_inputs; I ++)

X [I] = atoi (av [I + 1]);

}

Void scoot_over (int jj)

{Int k;

For (k = num_y-1; k> jj; k ++)

Y [k] = y [k-1];

}

Void insert (int new_y)

{Int j;

If (num_y = 0) {// y empty so far, easy case

Y [0] = new_y;

Return;

}

// Need to insert just before the first y

// Element that new_y is less

For (j = 0; j <num_y; j ++ ){

If (new_y <y [j]) {

// Shift y [j], y [j + 1],... rightward

// Before inserting new_y

Scoot_over (j );

Y [j] = new_y;

Return;

}

}

}

Void process_data ()

{

For (num_y = 0; num_y <num_inputs; num_y ++)

// Insert new y in the proper place

// Among y [0],..., y [num_y-1]

Insert (x [num_y]);

}

Void print_results ()

{Int I;

For (I = 0; I <num_inputs; I ++)

Printf ("% d", y [I]);

}

Int main (int argc, char ** argv)

{Get_args (argc, argv );

Process_data ();

Print_results ();

}
Let's compile:

Gcc-g-Wall-o insert_sort ins. c

Note that we should use the-g option to tell the compiler to save the symbol table in the executable file-the memory address corresponding to the variables and code in our program.

Now let's start running. We use the "starting from scratch" principle. First, we use two numbers for testing:

./Insert_sort 12 5

We found that the program did not exit, and it seems to have entered an endless loop. We started to use ddd to debug this program:

Ddd insert_sort

Run the program and input two parameters:

R 12 5

At this time, the program continues running and does not exit. Press Ctrl + C to pause the program execution.

(GDB) r 12 5
^ C
Program received signal SIGINT, Interrupt.
0x080484ff in insert (new_y = 3) at insert_sort.c: 45
/Home/gnuhpc/MyCode/Debug/Chapter_01/insert_sort/pg_019/insert_sort.c: 45: 939: beg: 0x80484ff
(GDB)

We can see that the program stops at 49th rows. Let's take a look at the current num_y value:

(GDB) p num_y
$1 = 1

$1 indicates the first variable you want GDB to tell you. After finding this place, let's see what happened at num_y = 1. We have the insert function (row 27th) set the breakpoint (you can also directly use break insert to set the breakpoint at the entry of this function), and set GDB at the breakpoint 1 (you can view the breakpoint through the info break command) only when num_y = 1:

(GDB) B 27
Breakpoint 1 at 0x80484a1: file insert_sort.c, line 27.
(GDB)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.