CSSE 132 Homework Review · Exam Study
Homework 6 Review + Solutions: Strings, Storage, and Streams
Revisit your submitted work: trace storage, calculate exact string sizes, and read files one successful line at a time. Try each practice question before opening its solution. Allow about 20 minutes for the full code walkthroughs.
Why This Matters
A pointer needs a live target, a C string needs a terminator, and an input buffer holds new data only after a successful read. Homework 6 combines these rules. The current exam study guide identifies Homework 6 as supporting practice for buffer/string handling, file input, and ownership. The connections below identify transferable skills, not promises about particular exam questions.
The solutions follow the current starter contracts. Historical answer files contain a few inconsistencies: the expansion hint suggests memcpy even though the explicit rule permits only strlen from string.h; the vowel-helper hint refers to HW4, but those helpers are in current Homework 5. The examples below follow the explicit restriction, check allocations, and close opened streams.
1. Allocate the Struct Before Using Its Fields
Original goal: Explain why db_entry crashes even after removing the print call, then repair it by inserting code.
Step-by-step solution
- Declaring struct db_entry *e creates only a pointer with an indeterminate value.
- The first e->name assignment already dereferences that invalid pointer. Removing a later print cannot repair it. This is undefined behavior; a crash is not guaranteed.
- Allocate the pointed-to struct after line 16, before line 17 writes a field. Free it before line 20, after its last use.
Final answer
e = malloc(sizeof *e); // insert after line 16
if (e == NULL) return 1;
/* Existing field assignments and dbe_print(e) go here. */
free(e); // insert before line 20
What should you learn? sizeof *e sizes the target object; sizeof e sizes the pointer. Allocating the struct does not allocate copies of the strings.
Exam connection: Trace pointer targets and ownership before explaining a memory error; these support the output-pointer questions in the exam guide.
Try one yourself
A struct has three pointer fields on the course ARM64 system. How many bytes does its allocation need? Must you also free string literals stored in those fields?
Practice solution and reasoning
24 bytes for the three 8-byte fields. Use sizeof *p. Free the allocated struct once; never free its literal targets.
2. Find a File’s End Position
Original goal: Fill the buffered-I/O blanks to open a file, obtain its size, and close it.
Step-by-step solution
- Open filename in read mode to obtain a FILE pointer.
- Seek zero bytes relative to SEEK_END. Seeking changes the position without reading the contents into a buffer.
- Read the end position with ftell, then close the stream.
Final answer: blanks in order
f = fopen(filename, "r");
fseek(f, 0, SEEK_END);
size = ftell(f);
fclose(f);
The assignment skeleton assumes a valid argument, successful operations, and a size fitting int. For a seekable regular file on course Linux, the end position is its byte length. In revised code use long size and %ld: ftell returns long and signals failure with -1L. Check argc, fopen against NULL, and fseek for a nonzero error before using the result. Pipes and terminal input need not support seeking.
What should you learn? A file position counts bytes from the start; it is separate from a string’s length or buffer capacity.
Exam connection: Buffered open/seek/tell/close tracing is practiced in the I/O worksheets; it reinforces resource handling used by later file and socket programs.
Try one yourself
A file contains exactly the bytes A, B, and newline. What does ftell report after seeking to its end? Where must you seek before reading its first byte?
Practice solution and reasoning
3, because the newline occupies one byte on course Linux. Use fseek(f, 0, SEEK_SET) to return to byte zero.
3. Measure and Build an Expanded String
Original goal: Implement expand_str_len and expand_str for exactly one non-nested N*(part) pattern, with N from 1 to 9.
Step-by-step solution
- Find the star. Only its immediately preceding digit is the repeat count; earlier digits belong to the prefix.
- Record the interior start and closing parenthesis. Calculate prefix + repeat count × interior length + suffix + 1.
- Allocate that exact byte count. Copy prefix, each repetition, and suffix with a separate output index. Append one terminator.
Trace before copying
Input: "Q3*(ab)Z"
Regions: prefix Q | N=3, part ab | suffix Z
Output: Q | ab | ab | ab | Z | \0
Bytes: 1 + 3*2 + 1 + 1 = 9Final answer: problems.c, expansion functions
| C code | What this does |
|---|---|
| The contract guarantees the delimiters. Exclude the digit and punctuation from the output; include the null terminator. |
| Allocate the size computed by the helper. Keep source boundaries separate from the output position. |
| The repeated source index restarts each time; out only advances. Character copying honors the restriction against string.h functions other than strlen. |
What should you learn? Lengths exclude punctuation that is syntax. The output index must never reach the allocated size before writing the final terminator. Input sizes are assumed to fit the starter’s int return type.
Exam connection: Practice tracing indices and allocated bytes; these are the same bounds and terminator skills the exam guide emphasizes for buffers.
Try one yourself
Expand "12R2*(xy)!". Give the output, the allocation size, and which digit controls repetition.
Practice solution and reasoning
"12Rxyxy!": eight characters plus a terminator = 9 bytes. The 2 immediately before * controls repetition. The prefix remains "12R".
4. Return a Newly Allocated Pig-Latin Word
Original goal: Implement pigify: empty input gives a new empty string; a vowel-leading word gains yay; otherwise move only its first character and append ay.
Step-by-step solution
- Measure the input and determine the case before allocating.
- For length n: empty needs 1 byte; vowel needs n+4; consonant needs n+3.
- Fill the new block, terminate it, and return it without freeing it. Preserve case.
Final answer: problems.c, pigify
| C code | What this does |
|---|---|
| Identify upper- and lowercase vowels. This inline scan has the role of the Homework 5 vowel helper; you can reuse that helper instead. |
| For vowels, copy all letters then yay. Otherwise copy from index 1, append the first letter, then ay. Empty input skips all letters and still gets its own terminator. |
What should you learn? Returning an address does not end a heap allocation’s lifetime. The caller uses the result and frees it exactly once.
Exam connection: Follow the allocate → return → use → free ownership chain, which also supports helpers that provide allocated results through output pointers.
Try one yourself
What are the outputs and allocation sizes for "Owl", "drum", and the empty string?
Practice solution and reasoning
"Owlyay" needs 7 bytes; "rumday" needs 7; the empty string needs 1. Only d moves in drum, not the whole consonant cluster dr.
5. Read, Trim, Convert, Print, Free
Original goal: Create platin.c to read one word per line using fgets and stop at an empty line.
Step-by-step solution
- Reserve 102 bytes for at most 100 word characters, a newline, and a terminator.
- Process only successful reads. Remove a newline when present; do not blindly remove the last character.
- Stop on an empty word, otherwise convert, print one line, and free the result. EOF also ends the loop.
Final answer: platin.c
| C code | What this does |
|---|---|
| fgets keeps a newline when it fits. A blank line is a successful read; EOF makes fgets return NULL. A last word without a newline keeps its final character. |
| Each iteration owns one new string and releases it after printing. The supplied Makefile compiles platin.c alone; including problems.c supplies its functions. Do not add a main to problems.c. |
What should you learn? A successful read and a nonempty word are different conditions. The + and − symbols in the PDF mark input/output; the program never prints them.
Exam connection: Trace state changes after each read. This supports the exam guide’s emphasis on checking buffer contents and return values before using text.
Try one yourself
Input is "oak\n\npear\n". What prints? What if the input is just "oak" followed by EOF, without a newline?
Practice solution and reasoning
Only "oakyay" and one newline print in the first case: the blank line stops processing before pear. The EOF case also prints "oakyay" once, preserving the k.
6. Compare Lines at the Same Position
Original goal: Create sameLine.c: accept two filenames and print lines whose contents and line numbers both match.
Step-by-step solution
- Validate argc == 3 before reading argv[1] or argv[2]. Open both files; if the second fails, close the first.
- Read one line from each stream per round. Compare only when both reads succeed; stop when either ends.
- Count all pairs starting at 1. Print matching text with its existing newline, then close both streams.
| Line | File A | File B | Print? |
|---|---|---|---|
| 1 | red | red | 1: red |
| 2 | blue | gold | No |
| 3 | gold | gold | 3: gold |
Final answer: sameLine.c
| C code | What this does |
|---|---|
| Validate arguments first. A failed open has no stream to close. |
| If the second open fails, release the already opened first stream before returning. |
| The contract guarantees lines shorter than 512 bytes, with newlines, so these buffers fit a whole line and terminator. Compare contents, not addresses; printing left already prints its newline. |
What should you learn? Two equal strings at different positions do not qualify. Cleanup belongs on early-return paths as well as the successful path.
Exam connection: Use paired-read and cleanup reasoning in file programs; transfer return-value checking to socket calls while remembering recv does not automatically append a terminator.
Try one yourself
A has cat, dog, eel on lines 1–3; B has dog, dog on lines 1–2. Which lines print, and why does line 3 not print?
Practice solution and reasoning
Only "2: dog" prints. Line 1 differs; B ends before a third pair exists. Searching A for B’s line 1 would solve a different problem.
Common Mistakes
Allocate sizeof *e before field access; string literals remain separate.
Count it even for empty results. Expansion syntax disappears from the output.
Check fgets first; trim only a newline that is actually present.
Free each converted string and close both files, including partial-open failure paths.
Quick Reference and Testing
| Operation | Rule |
|---|---|
| Expanded allocation | prefix + N × part + suffix + 1 bytes |
| pigify allocation | empty: 1; vowel: n+4; consonant: n+3 |
| fgets(buf, capacity, stream) | At most capacity−1 characters, then a terminator on success; may retain newline. |
| ftell(stream) | long position; −1L on failure. Seekable regular files assumed here. |
| Line comparison | Compare contents after both reads succeed; count every pair. |
make test
./test
make platin
./test_platin.sh
make sameLine
./test_sameLine.shRun in Homework 6 on the course Linux VM. Inspect each summary: three unit-test groups, three platin cases, seven sameLine cases. The platin script calls make clean, so rebuild ./test before rerunning it. The sameLine script uses a course Linux reference executable. Add empty strings/files, uppercase vowels, N=1 and N=9, a final word without a newline, unequal file lengths, and second-file open failure to your checks.
After reviewing Homework 6, I should be able to...
- Draw a pointer, its heap target, and separate string storage.
- Locate the first invalid dereference and insert allocation and cleanup in the correct order.
- Fill the buffered open/seek/tell/close calls and explain their assumptions.
- Derive the exact allocation size of an expanded or pig-latin string.
- Trace independent source and destination indices and place the terminator.
- Distinguish a blank input line from EOF and preserve a final non-newline character.
- Compare corresponding lines, explain output numbering, and close both streams.
- Identify the owner of each returned allocation and release it after its final use.
For further practice, return to heap allocation, buffered I/O, line input, and the exam study questions.