CSSE 132 · Lecture 23 · Review draft

When C Code Looks Correct: Memory Errors, Heap Allocation, and Pointers

A string could pass a content check and still fail when the test released it.

Why this matters

Checking the characters is only one step. You also need to know where the string is stored and whether the caller can safely pass its address to free.

1. Why did it fail after the answer looked right?

munmap_chunk(): invalid pointer
Aborted (core dumped)

This message can appear when free receives an invalid pointer. The mistake may have happened earlier; the exact diagnostic depends on the runtime.

Follow the exam test

  1. Input: the string literal "No brackets here".
  2. Content check: the returned string has the expected characters.
  3. Cleanup: the test calls free on the returned pointer.

If the function returns the input address instead of a new heap allocation, step 2 can pass and step 3 is invalid: a string literal cannot be freed.

Debugging question: Where did the returned pointer get its address? Trace it back to the allocation or assignment.

2. Three different memory problems

Problem and illustrative C fragmentWhat happens / prevention
int *p = NULL; *p = 42;
Invalid access
Dereferencing NULL has undefined behavior, often a segmentation fault at the access. Check pointers before dereferencing; a crash is not guaranteed.
char *p = malloc(6); p = NULL;
Memory leak
If allocation succeeded and this was its last pointer, its address is lost. Usually no immediate crash. Keep the address until its last use, then free it before losing it.
char *p = "hello"; free(p);
Invalid free
A literal is not a heap allocation. Undefined behavior may cause an allocator abort or no obvious symptom. Free only a current allocation's starting address, once; never a literal, local array, interior pointer, or already freed block.

free(NULL) is allowed. A leak wastes storage; an invalid access or invalid free violates C's rules. These errors do not all produce the same message.

Three memory-error tracesThree separate cases, not a sequence: an invalid access, an unreachable heap block, and an invalid release.NULL → accessinvalid accessheap block, no ownerleak: address lostliteral → freeinvalid release
Three separate cases, not a sequence: an invalid access, an unreachable heap block, and an invalid release.

3. Assignment changes an address; copying changes bytes

char *result = malloc(strlen(str) + 1);
if (/* no brackets: illustrative condition */) {
    result = str;  // replaces the saved heap address
    return result;
}

Before assignment, str refers to the original input and result refers to a separate allocation. Use symbolic addresses S and H; these are different storage regions.

Before assignmentBefore: str points to input S; result points to newly allocated block H. str does not point to result.str → Soriginal inputresult → Hseparate pointerH: uninitialized bytesnew heap allocation
Before: str points to input S; result points to newly allocated block H. str does not point to result.
After result equals strAfter result = str, both pointers refer to S. H still exists but its only saved address was overwritten.str → Soriginal inputresult → Ssame input addressH: unreachableallocation leaked
After result = str, both pointers refer to S. H still exists but its only saved address was overwritten.

No characters moved. The allocation is leaked if no other pointer retains H. Returning S also breaks the caller's expectation of a separately allocated result. A literal or stack array cannot be freed; even if S were a heap block, aliases would still require agreement about who frees it and when.

Adding '\0' does not restore the lost address. Writing through result after this assignment may modify the input; writing into a literal is undefined behavior. In contrast, memcpy(result, str, strlen(str) + 1) copies bytes into the separate heap block while preserving its address. This assumes successful allocation, enough space, and nonoverlapping regions.

return *str; returns the first character's value, not a string pointer. In a function returning char *, that is a type error requiring a diagnostic; use the pointer to the intended string.

4. Make a copy with a clear owner

A complete copyString function
C codeWhat this does
#include <stdlib.h>
#include <string.h>
Declare malloc, free, strlen, and memcpy.
char *copyString(const char *str) {
    char *result = malloc(strlen(str) + 1);
Assume str is a valid null-terminated string. Reserve the characters plus one byte for the terminator.
    if (result == NULL)
        return NULL;
Do not copy through a failed allocation.
    memcpy(result, str, strlen(str) + 1);
    return result;
}
Copy the terminator too. Return the heap address; the caller becomes responsible for freeing it.
Copy bytes without changing pointersCopying hello needs six bytes: five letters and the null terminator. S and H retain different addresses.str → S: hello\0input stays intactmemcpy: 6 bytesincludes terminatorresult → H: hello\0independent heap copy
Copying hello needs six bytes: five letters and the null terminator. S and H retain different addresses.
char *answer = copyString("hello");
if (answer != NULL) {
    printf("%s\n", answer); // requires <stdio.h>
    free(answer);           // exactly once, after last use
}
Pointer lifetime and heap lifetimeThe local pointer variable ends with the call. Its heap block survives; the caller retains the returned address and releases the block.local result → Hfunction call framecaller answer → Hafter function returnH: heap byteslive until free(answer)
The local pointer variable ends with the call. Its heap block survives; the caller retains the returned address and releases the block.

Common mistakes / quick reference

  • p = q copies an address; memcpy(p, q, n) copies n bytes.
  • strlen excludes '\0'; copying a whole string needs one extra byte.
  • Printing correctly does not establish that a pointer is valid for free.

Check yourself

  1. Why can a string comparison pass before free fails?
  2. After malloc(6) followed by result = "hello", where is the heap address?
  3. How many bytes must memcpy copy for "cat"?
  4. Who frees the heap block returned by copyString?
Answers
  1. The bytes can be correct while the pointer refers to storage that free cannot release.
  2. Lost, if result held its only copy; assignment did not release the allocation.
  3. Four: three characters and '\0'.
  4. The caller, after its last use of the returned string.