This guide walks through debugging a C++ program that contains logical errors.
The program is supposed to compute:
[ (X^0)/0! + (X^1)/1! + (X^2)/2! + (X^3)/3! + (X^4)/4! + \dots + (X^n)/n! ]
for given inputs x and n.
However, it always outputs infinity (inf), regardless of the input.
We will trace the issue step by step using GDB.
Download the buggy program:
➡️ broken.cpp
Compile with debugging info: g++ -g broken.cpp -o broken ./broken
gdb broken
Set a breakpoint at line 43:
(gdb) b 43
This corresponds to: double seriesValue = ComputeSeriesValue(x, n);
Run the program:
(gdb) run
When prompted, enter:
x = 2 n = 3
Expected output: 5
Debugger stops at the breakpoint: Breakpoint 1, main () at broken.cpp:43 43 double seriesValue = ComputeSeriesValue(x, n);
To step into the function:
(gdb) step
Execution moves to: 17 double seriesValue=0.0;
Continue stepping: (gdb) next 18 double xpow=1; (gdb) n 20 for (int k = 0; k <= n; k++) { (gdb) n 21 seriesValue += xpow / ComputeFactorial(k) ; (gdb) step
Now inside ComputeFactorial():
7 int fact=0; //
Use backtrace to see where we are:
(gdb) bt #0 ComputeFactorial (number=0) at broken.cpp:7 #1 0x08048907 in ComputeSeriesValue (x=2, n=3) at broken.cpp:21 #2 0x08048a31 in main () at broken.cpp:43
Step through the loop:
(gdb) next 9 for (int j = 0; j <= number; j++) { (gdb) n 10 fact = fact * j; (gdb) n 9 for (int j = 0; j <= number; j++) {
Check variable value:
(gdb) print fact $2 = 0 Continue: (gdb) n 13 return fact; (gdb) quit
🚨 Bug Found
fact was initialized as 0 Factorial is computed as: fact = fact * j;
This guide explains how to debug a program that crashes due to a segmentation fault and produces a core dump.
Download the sample program:
➡️ testit.c
Compile with debugging information: gcc -g testit.c -o testit
Execute the binary: ./testit
Output: Segmentation fault (core dumped) A core dump file named core will be generated.
- Enable Core Dumps Temporarily Run this before executing your program:
ulimit -c unlimited
This tells the shell to allow core files of unlimited size.
Start GDB with both the program and the core file:
gdb testit core
Expected Output: GNU gdb 19991004 Core was generated by `testit'. Program terminated with signal 11, Segmentation fault. Reading symbols from /usr/lib/libstdc++-libc6.1-1.so.2...done. Reading symbols from /lib/libm.so.6...done. Reading symbols from /lib/libc.so.6...done. Reading symbols from /lib/ld-linux.so.2...done. #0 0x804851a in main () at testit.c:10 10 temp[3] = 'F';
The debugger shows the crash occurred at line 10:
temp[3] = 'F'; Looking at the declaration on line 5:
char *temp = "Paras"; temp is a pointer to a string literal.
String literals in C/C++ are read-only, so attempting to modify them causes a segmentation fault.