You found in Chapter 1 that in GDB you can print the value of a variable using the print
command and that this can be done in DDD and Eclipse by moving the mouse pointer to an instance of the variable anywhere in the source code. But both GDB and the GUIs also offer much more powerful ways to inspect variables and data structures, as we will see in this chapter.
Following is a straightforward (though not necessarily efficient, modular, etc.) implementation of a binary tree:
// bintree.c: routines to do insert and sorted print of a binary tree #include <stdio.h> #include <stdlib.h> struct node { int val; // stored value struct node *left; // ptr to smaller child struct node *right; // ptr to larger child }; typedef struct node *nsp; nsp root; nsp makenode(int x) { nsp tmp; tmp = (nsp) malloc(sizeof(struct node)); tmp->val = x; tmp->left = tmp->right = 0; return tmp; } void insert(nsp *btp, int x) { nsp tmp = *btp; if (*btp == 0) { *btp = makenode(x); return; } while (1) { if (x < tmp->val) { if (tmp->left != 0) { tmp = tmp->left; } else { tmp->left = makenode(x); break; } } else { if (tmp->right != 0) { tmp = tmp->right; } else { tmp->right = makenode(x); break; } } } } void printtree(nsp bt) { if (bt == 0) return; printtree(bt->left); printf("%d\n",bt->val); printtree(bt->right); } int main(int argc, char *argv[]) { int i; root = 0; for (i = 1; i < argc; i++) insert(&root, atoi(argv[i])); printtree(root); }
At each node, all elements of the left subtree are less than the value in the given node, and all elements of the right subtree are greater than or equal to the one in the given node. The function insert()
creates a new node and places it in the proper position in the tree. The function printtree()
displays the elements of any subtree in ascending numerical order, while main()
runs a test, printing out the entire sorted array.[13]
For the debugging examples here, suppose that you had accidentally coded the second call to makenode()
in insert()
as
tmp->left = makenode(x);
instead of
tmp->right = makenode(x);
If you run this buggy code, something immediately goes wrong:
$ bintree 12 8 5 19 16 16 12
Let's explore how the various inspection commands in the debugging tools can help expedite finding the bug.
[13] By the way, note the typedef
in line 12, nsp
. This stands for node struct pointer, but our publisher thinks it's No Starch Press.