CSSE 132 Homework Review

Homework 5 Review: String Storage and Memory Lifetime

Follow every allocation from creation through its final use. Allow about 10 minutes. Use the examples to reason through the written questions and plan the coding portion.

Why This Matters

Homework 5 connects string operations to storage lifetime. A pointer can contain an address even when that address is no longer valid to use. For every string, track its capacity, its terminator, and who owns its storage.

Written Portion: Separate the Pointer from Its Storage

Core idea: a pointer variable and the object it points to have separate locations and lifetimes. A local pointer can point to a heap block that survives the function call. A pointer can also remain in scope after its target has been freed; that does not make the target usable.

Worked Example: Two Objects, Two Lifetimes

void showLabel(void) {
    char local[] = "oak";        // automatic array: four bytes
    char *label = malloc(4);      // local pointer, heap target
    if (label == NULL) return;
    memcpy(label, local, 4);      // includes the null terminator
    printf("%s\n", label);
    free(label);                 // release the heap block once
}

local has automatic storage duration, normally on the stack in the course model. Its lifetime ends when the function returns. label is another automatic object, but the four bytes returned by malloc are on the heap. Only that allocated block needs an explicit free. Passing an automatic array's address to free is undefined behavior.

Free the original allocation address exactly once after its last use. Do not free a pointer into the middle of the allocation. free(NULL) is permitted. The pointer's type alone does not tell you whether its target is eligible to be freed.

Ownership: Who Releases a Returned String?

When a function returns a newly allocated string, its caller usually becomes responsible for freeing it. Returning a pointer copies an address; it neither copies the allocation nor ends its lifetime. Write down a timeline: allocate → check success → fill → return → use → free.

If each request allocates 40 bytes and loses the only pointer without freeing it, 1,000 requests leak 40,000 data bytes, excluding allocator overhead. A short test may print correct text while missing that accumulating problem. Process exit reclaims process memory, but a long-running server needs to release allocations during execution. A leak can cause memory pressure; it does not guarantee a crash at a particular time.

For each written program, mark the allocation, every use, and the intended owner. If the owner loses the pointer before freeing it, look for a leak. If the program frees the block before its final use, look for a dangling pointer and use after free. Returning the address of a local array has a different cause: that automatic array's lifetime ends on return.

Written Portion: Count Bytes, Then Check Lifetime

Worked Example: A Terminator Is Part of the String

char source[] = "birch";  // b i r c h \0: six bytes
char copy[6];
memcpy(copy, source, sizeof source);

Five visible characters require six bytes. Copying only five leaves copy without a guaranteed terminator. Printing it with %s could read beyond its bounds. Copying seven bytes would also be invalid here: neither array supplies seven accessible bytes.

memcpy copies exactly its byte count; it does not stop at '\0' or add one. Check both the readable source range and the writable destination range. A large destination alone does not justify reading that many bytes from a short source.

For a fixed array with capacity C, a string fits when its length plus one is at most C. If longer inputs are possible, decide whether the program should reject them, deliberately truncate and terminate them, or allocate enough storage for the entire string. Explain that choice rather than assuming that a larger byte count makes a copy safer.

Worked Example: An Alias Does Not Extend Lifetime

char *alias = label;  // both pointers name the same live block
/* Use the string while its allocation is alive. */
free(label);          // ends that block's lifetime
label = NULL;         // changes only this pointer

This fragment assumes label holds a successful allocation. After the free, alias is dangling. Neither printing through it nor freeing it again is valid. Setting label to NULL does not repair other aliases. Even if the old bytes appear unchanged, reading them is undefined behavior.

When reviewing the homework's second print, reason from the allocation's lifetime. Do not predict a particular garbage string or assume that undefined behavior always crashes. Similarly, a successful output comparison does not prove that a byte copy stayed within bounds.

Coding Portion: Plan the Contract

startsWith and startsWithVowel: compare characters

startsWith asks whether the first input character occurs anywhere in targets. For "map", "xyz m", the result is 1 because the target set contains m. For an empty input or an empty target set, there is no matching initial character: return 0. Do not search the rest of the input.

For vowel detection, account for both lowercase and uppercase vowels, and reuse your helper. The starter allows strlen but no other library functions in these two functions.

string2num: accumulate decimal place values

For "307", the running value progresses 0 → 3 → 30 → 307. Each new digit shifts the existing value one decimal place before contributing its digit value. A character such as '7' becomes the integer 7 by subtracting '0'.

The contract assumes properly formed nonnegative decimal text (the tests include "0"). Focus on conversion; do not call atoi or other forbidden library helpers. Keep the supplied integer return type and work within its representable range.

skipper: count retained characters before allocating

For "planet", indices 0, 2, and 4 give "pae". For "stone", indices 0, 2, and 4 give "soe". Both outputs need three character bytes plus one terminator byte. Empty input still needs one byte for a new empty string.

Plan two positions: the input position advances by two, while the output position advances by one. Calculate the exact number of selected characters before allocating, reserve the terminator, and check the allocation. Return the new block without freeing it; the caller owns it. Do not return a local array or overwrite the caller’s input.

These are function contracts and reasoning steps, not complete coding solutions. Keep the starter names and signatures and do not add main to problems.c.

Common Mistakes

Pointer and target treated as one object

A local pointer can name a heap allocation with a separate lifetime.

Only visible characters allocated

A C string also needs its null terminator, including an empty string.

memcpy treated as string-aware

Its byte count must fit both source and destination; it does not stop at a terminator.

Correct output treated as proof of safety

Leaks and invalid reads may escape a short output test.

Quick Reference and Testing

make test
./test

Run inside Homework 5 on the course Linux VM. Read the individual results and summary. Test empty strings, odd/even input lengths, uppercase vowels, and a target set with no match. Submit problems.c as the homework directs.

Rule or operationWhat to check
strlen(text) + 1Bytes for a full string copy, including the terminator.
memcpy(dst, src, n)Both ranges allow n bytes; no terminator is added.
malloc / freeCheck success; keep the block alive through its last use; free it once.
Returned heap stringIdentify the caller responsible for releasing it.
Every other characterInput indices 0, 2, 4, …; reserve a separate output terminator.

Check Yourself

  1. Where is the block pointed to by a local malloc result?
  2. How many bytes hold a copy of "lamp"?
  3. Why does unchanged text after free prove nothing?
  4. Which characters does skipper retain from "abcde"?
Answers and reasoning
  1. On the heap; the local pointer is a separate object.
  2. 5: four visible characters and one null terminator.
  3. The block’s lifetime has ended; reading it is undefined behavior regardless of its apparent bytes.
  4. a, c, e, giving "ace"; the new string needs four bytes.