CSSE 132 Homework Review · Exam Study
Homework 7 Review + Solutions: Words, Buffers, and Output Pointers
Use your submitted Homework 7 to practice tracing word boundaries, streaming file data, and returning a heap array through a pointer. Try each new question before opening its solution. Allow about 20 minutes.
Read the current contracts first
The current assignment has two parts: the four functions in problems.c and the censor program. Word characters are ASCII A–Z and a–z. Digits, punctuation, whitespace, and the null terminator separate words. Line-length files end in a newline and have no fixed maximum line or file length. Censor has a different contract: each line contains fewer than 1024 characters and words do not cross lines.
The final review guide includes C arrays, pointer arithmetic, pointers for output, and buffered file I/O. The exam connections below describe those transferable skills; use the current exam page for preparation and scope.
1. Recognize a Word and Measure Its Prefix
Original goal: Implement isWordChar without function calls, then implement wordlen, including a NULL input.
- Test the two letter ranges independently and combine with logical OR.
- For wordlen, reject NULL before indexing. Count consecutive letters beginning at index zero; do not skip separators.
int isWordChar(char x) {
return ('A' <= x && x <= 'Z') ||
('a' <= x && x <= 'z');
}
int wordlen(char *str) {
if (str == NULL) return 0;
int n = 0;
while (isWordChar(str[n])) n++;
return n;
}
Final answer: wordlen("Code-quiz") is 4; wordlen(" Code") and wordlen(NULL) are 0.
What should you learn? A string terminator is a nonletter, so it naturally stops the scan. NULL is an address value and must be checked before reading memory.
Exam connection: Trace array indices and distinguish a null pointer from a terminating null character.
Try one yourself
Find wordlen("R2D2"), wordlen("-four"), and wordlen("seven!"). Why is strlen not a substitute?
Practice solution and reasoning
The answers are 1, 0, and 5. strlen counts every character before the terminator, including digits and punctuation; wordlen stops at the first nonletter.
2. Count Newlines in Bytes, Not a String
Original goal: Examine exactly len bytes, even if a null byte appears inside the buffer.
- Start the count at zero.
- Visit indices 0 through len−1 and increment only for a newline.
- When using fread, pass the number of bytes actually read, which can be smaller than the buffer capacity.
int countNewlines(char *buf, int len) {
int count = 0;
for (int i = 0; i < len; i++)
if (buf[i] == '\n') count++;
return count;
}
Final answer: For bytes {'A', '\0', '\n', 'B', '\n'}, len=4 gives 1 and len=5 gives 2.
What should you learn? A counted buffer need not be null terminated. Only the returned byte count identifies the readable input from this read. Assume len is nonnegative and buf supplies len accessible bytes.
Exam connection: Apply the same bounds reasoning to file and socket reads; their returned data is not automatically a C string.
Try one yourself
A 256-byte buffer receives 3 bytes: newline, x, newline. What length should you pass, and what is the count?
Practice solution and reasoning
Pass 3 and obtain 2. Passing 256 would inspect stale or uninitialized bytes beyond this read.
Trace across a buffer boundary
| Chunk (capacity 4 for illustration) | Completed lengths | Unfinished length |
|---|---|---|
ab\nc | [2] | 1 |
def\n | [2, 4] | 0 |
\n | [2, 4, 0] | 0 |
The word cdef spans two reads. Keep the unfinished length between reads; reset it only after a newline. A blank line contributes an array entry of zero.
3. Allocate and Return All Line Lengths
Original goal: Read an arbitrarily long file in chunks, allocate one int per newline, and write the array address and count into the caller’s variables.
- First pass: sum newline counts using successful fread results.
- Rewind the same seekable file. Allocate count × sizeof *lens bytes.
- Second pass: carry length between chunks; at each newline store it and reset it.
- Close the stream, then assign through both output pointers. The caller frees the array.
void getLineLengths(char *filename, int **linelens_addr,
int *numlines_addr) {
*linelens_addr = NULL;
*numlines_addr = 0;
FILE *in = fopen(filename, "rb");
if (in == NULL) return;
char buf[256];
size_t got;
int count = 0;
while ((got = fread(buf, 1, sizeof buf, in)) > 0)
count += countNewlines(buf, (int)got);
if (ferror(in) || fseek(in, 0, SEEK_SET) != 0) {
fclose(in);
return;
}
int *lens = NULL;
if (count > 0) {
lens = malloc((size_t)count * sizeof *lens);
if (lens == NULL) { fclose(in); return; }
}
int row = 0, length = 0;
while ((got = fread(buf, 1, sizeof buf, in)) > 0) {
for (size_t i = 0; i < got; i++) {
if (buf[i] == '\n') {
lens[row++] = length;
length = 0;
} else {
length++;
}
}
}
if (ferror(in)) { free(lens); fclose(in); return; }
fclose(in);
*linelens_addr = lens;
*numlines_addr = count;
}
Final answer: For "ab\ncdef\n\n", return count 3 and a heap array [2, 4, 0].
What should you learn? The buffer capacity bounds temporary storage, not file or line length. Assume a stable, seekable file ending in newline, valid output addresses, and counts and lengths representable as int. The displayed version leaves NULL/0 on open, seek, allocation, or read failure; this void interface cannot distinguish those failures from an empty file.
Exam connection: This combines the final review guide’s buffered I/O, heap allocation, and pointers for output; see the pointer-output walkthrough.
Try one yourself
For "xy\n\nz\n", give the array, count, and allocation expression. Which object does *linelens_addr name?
Practice solution and reasoning
[2, 0, 1], count 3, and 3 * sizeof *lens bytes. *linelens_addr names the caller’s pointer variable; storing lens there makes that variable point to the heap array.
Follow the two levels of indirection
Caller: int *lengths = NULL; int n = 0;
getLineLengths("input.txt", &lengths, &n);
linelens_addr (int **) → lengths (int *) → heap [2 | 4 | 0]
numlines_addr (int *) → n = 3
*linelens_addr = lens; // update caller's pointer
*numlines_addr = count; // update caller's integer
/* Caller uses lengths[0] through lengths[n-1], then: */
free(lengths);Assigning linelens_addr = &lens would only change the local parameter and would name a local variable. Do not free lens before returning it. For an empty file, this version returns NULL and zero; free(NULL) is valid.
4. Censor Complete Four-Letter Words
Original goal: Preserve every separator and replace only the two middle letters of each four-letter word.
- Validate the filename argument and open the input.
- Read a whole line with a 1024-byte buffer: at most 1023 input characters plus the terminator.
- Measure each whole word before changing it. For length four, replace offsets 1 and 2.
- Advance past the original whole word, or advance one byte over a separator. Print with fputs to preserve existing newlines.
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s file\n", argv[0]);
return 1;
}
FILE *in = fopen(argv[1], "r");
if (in == NULL) { perror(argv[1]); return 1; }
char buf[1024];
while (fgets(buf, sizeof buf, in) != NULL) {
char *p = buf;
while (*p != '\0') {
int n = wordlen(p);
if (n == 4) { p[1] = '*'; p[2] = '*'; }
p += n > 0 ? n : 1;
}
fputs(buf, stdout);
}
int failed = ferror(in);
fclose(in);
return failed ? 1 : 0;
}
Final answer: "This, seven; TEST42fine!" becomes "T**s, seven; T**T42f**e!".
What should you learn? p points inside buf; p[1] means the byte one position after p. After measuring a five-letter word, skip all five letters so its four-letter suffix is not censored. Censor does not allocate heap memory. Compile this main with the isWordChar and wordlen definitions above and stdio.h; problems.c itself must not contain main.
Exam connection: Trace pointer arithmetic, bounded line input, and exact output preservation. Homework 6’s successful-read checks and cleanup rules transfer directly.
Try one yourself
Censor "stone test-test 1234 ABCD". Explain why stone and 1234 stay unchanged.
Practice solution and reasoning
"stone t**t-t**t 1234 A**D". stone is one five-letter word; digits are separators, so 1234 contains no words. The hyphen separates two four-letter words.
Common Mistakes
fread adds no terminator. Inspect only its returned byte count.
Keep the partial length across chunks. The supplied sample includes a 4459-character line.
Write *linelens_addr, allocate ints rather than pointers, and leave the returned allocation alive.
Skip its entire measured length, even when its length is not four. Always advance over separators.
The historical solutions omit the NULL guard in wordlen and use a smaller censor buffer. The code here follows the current starter’s NULL contract and the assignment’s line bound. It also checks file operations instead of proceeding after a failed open.
Quick Reference and Testing
make test
./test
make censor
./test_censor.shRun in Homework 7 on the course Linux VM. Check all four Unity groups and the censor script’s three output comparisons. Add NULL and empty strings, embedded null bytes in a counted buffer, blank lines, an empty file, lines spanning many chunks, punctuation, mixed case, and censor input with no final newline. The line-length contract requires a final newline; the censor contract does not. Output tests alone do not verify allocation sizes, ownership, or file cleanup.
After reviewing Homework 7, I should be able to...
- Implement ASCII letter classification without library calls.
- Distinguish NULL, an empty string, and a leading separator.
- Count newlines beyond an embedded null byte using explicit bounds.
- Explain both passes and carry a partial line across chunk boundaries.
- Allocate exactly one int per line, including blank lines.
- Draw int ** → caller pointer → heap array and identify who frees it.
- Censor whole words while preserving punctuation, case, and newlines.
- Check read results and close streams on success and error paths.
Continue with pointers for output, buffered I/O, and Exam 3 preparation.