Week 5 Tutorial — Testing, Debugging, Performance Tuning

  1. (Testing) Suggest suitable classes of test inputs and give specific representatives for a function

    int factorial(int n) { ... }
    

    to compute the factorial of an integer n. Ensure that your tests cover both valid inputs and invalid inputs.

  2. (Debugging) What, if anything, is wrong with the following function that checks whether a given number is prime? (Assume that n≥1.)

    int isPrime(int n) {
       int rootn;
       rootn = sqrt(n);
       int i;
       for (i = 2; i <= rootn; i++) {
          if (n % i == 0) {
             return 0; // this violates the style guide: for demo purposes only
          }
       }
       return 1; // TRUE
    }
    

  3. (Debugging, Performance) The following function searches for a word in a list of words. It contains two bugs.

    // search for word in an array of words of size nwords
    // if found, returns index of array element containing word
    // if not found, returns -1
    int findWord(char *word, char *wordList[], int nwords) {
       int i, found;
       for (i = 0; i < nwords; i++) {
          if (strcmp(wordList[i],word) == 0) {
             found = i;
          } else {
             found = -1;
          }
       }
       return found;
    }
    

    1. Describe the bugs and suggest fixes.
    2. Once the function is correct, suggest approaches to improve its performance.
  4. (Testing) The function:

    char *strncat(char *dest, char *source, int n);
    

    appends the source string to the destination string by overwriting the null byte that terminates the string dest, copying up to n characters from the source, and then writing a new null byte. A pointer to the extended string dest is also returned. The string dest must be long enough to accommodate the extended string.

    An example of its use is:

    char code[9] = "comp";
    printf("%s\n", strncat(code, "1921rubbish", 4));
    printf("code = %s\n", code);
    

    The output would be:

    comp1921
    code = comp1921
    

    1. Write the strncat() function.
    2. Provide a set of tests to check that your function behaves correctly.