A sample program – buggie

We'll need a program to debug to experience gdb. Let's create a new project by running cargo new buggie. Our program will have a single function, fibonacci, which takes a position of n as usize, and gives us the nth Fibonacci number. This function assumes that the initial values of the Fibonacci numbers are 0 and 1. The following code is the program in its entirety:

1 // buggie/src/main.rs
2
3 use std::env;
4
5 pub fn fibonacci(n: u32) -> u32 {
6 let mut a = 0;
7 let mut b = 1;
8 let mut c = 0;
9 for _ in 2..n {
10 let c = a + b;
11 a = b;
12 b = c;
13 }
14 c
15 }
16
17 fn main() {
18 let arg = env::args().skip(1).next().unwrap();
19 let pos = str::parse::<u32>(&arg).unwrap();
20 let nth_fib = fibonacci(pos);
21 println!("Fibonacci number at {} is {}", pos, nth_fib);
22 }

Let's take this program for a spin:

We ran the program with 4 as the argument, but we can see a 0 as the output, which should have been 3. We have a bug here. While we could use the println! or dbg! macro to easily tackle this bug, we'll use gdb this time.

Before we run gdb, we need to plan our debugging session. This includes deciding where to look inside our program and what to look for. As a starting point, we'll examine the contents of the main function and then step into the fibonacci function. We'll set two breakpoints, one at main and another within fibonacci.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset