2009-09-16

Post date: Sep 16, 2009 10:02:54 PM

Objective

    • Learn how to use a debugger, and use it to examine bit-manipulation algorithms to study how the code works. Each source file provided has a regular, obvious version, and a fast, not-so-obvious version.

Important: in order to generate an executable that is suitable for source-code level debugging, you must pass the -g flag to gcc when compiling. Otherwise gdb could only provide debugging at machine code instruction level.

Exercises

    • Count the number of "one" bits in an integer's binary representation (see countbits.c attached). For a text-book explanation of how the fast version works, see Hacker's Delight by Henry S. Warren.
    • Compute the next power of 2 that is greater than or equal to a given integer (take home exercise, see next poweroftwo.c attached). See Algorithm to find the next-highest power of two in Wikipedia for an explanation of how the fast version works.

Emacs commands:

    • C-x C-c (quit)
    • C-x C-s (save)
    • C-k (cuts from cursor to end of line)
    • C-y (paste)
    • See Enabling Font Lock for how to turn on syntax coloring.

GDB commands:

    • r (run) start over the program.
    • c (continue) execute from where we last stopped.
    • n (next) runs one line of code; executes functions like one instruction and does not step into the function.
    • s (step) runs one line of code; steps into function calls.
    • b (breakpoint) makes gdb stop at a certain location when execution passes through it.
      • b count_one_bits /* break at function */
      • b countbits.c:4 /* break in file countbits.c at line number 4 */
    • p (print) a variable or an expression. Examples:
      • p i /* prints variable i */
      • p /x n /* prints variable n in hexadecimal */
      • p (n & 1) /* prints the result of (n & 1) */
    • h (help)
    • q (quit)

Fun