Compiling and debugging
For this example, we'll use a program that reads a list of numbers followed by 0, and stores them in an array.
It then creates a linked list with the same numbers in it. Finally, it calculates the sum of the numbers
in the array and in the linked list.
Download the program's source code files: sum.cpp and header file
node.h.
Compiling
Once the files are downloaded, compile using...
% g++ -o sum sum.cpp
Did the program compile without errors or warnings? What went wrong?
Run-time errors
Now that everything compiles, run the executable with some data:
% ./sum
Enter numbers to sum below (separated by spaces).
Enter 0 (zero) as the last number.
5 6 7 0
Segmentation fault
What is the problem?
Logic errors
Go ahead and fix the error. Save your changes, recompile the program, and run it again.
% g++ -o sum sum.cpp
% ./sum
Enter numbers to sum below (separated by spaces).
Enter 0 (zero) as the last number.
5 6 7 0
Enter 0 (zero) as the last number.
ArraySum = 13
ListSum = 0
The Segmentation fault has been eliminated!! However, now we have a logic error, since the sum should be 18, and we get 13 and 0!!
Again, we need more information! What can be done?
Fix the error, recompile and run it again.
% ./sum
Enter numbers to sum below (separated by spaces).
Enter 0 (zero) as the last number.
5 6 7 0
ArraySum = 13
ListSum = 0
We solved one problem! Now we need to figure out how to solve the other...
Original page created by Robert I Pitts.
Modified by Gali Diamant gali@cs.bu.edu