Skip to main content

1-11

Quest: page 21


  • How would you test the word count program ?
  • What kinds of input are most likely to uncover bugs if there are any ?

  • the wc int can overflow. Lets pretend the wc reaches the MAX value of int lets say its a uint16: then you could count 65536. When we reach MAX_VALUE +1 it's value would be 0 again. This happens in a lot of games and everywhere else. Nowadays it's less likely but can still happen. With uint64 we have a wider range.
int overflow
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

int main() {
u_int16_t c = 65535;
printf("value: %d\n", c);
c++;
printf("value: %d\n", c);
}
word count
#include <stdio.h>

#define OUT 0
#define IN 1

int main() {
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n') {
++nl;
}
if (c == ' ' || c == '\n' || c == '\t') {
state = OUT;
} else if (state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}