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
- Input: the string literal
"No brackets here". - Content check: the returned string has the expected characters.
- Cleanup: the test calls
freeon 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 fragment | What 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.
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.
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
| C code | What this does |
|---|---|
| Declare malloc, free, strlen, and memcpy. |
| Assume str is a valid null-terminated string. Reserve the characters plus one byte for the terminator. |
| Do not copy through a failed allocation. |
| Copy the terminator too. Return the heap address; the caller becomes responsible for freeing it. |
char *answer = copyString("hello");
if (answer != NULL) {
printf("%s\n", answer); // requires <stdio.h>
free(answer); // exactly once, after last use
}
Common mistakes / quick reference
p = qcopies 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
- Why can a string comparison pass before free fails?
- After malloc(6) followed by result = "hello", where is the heap address?
- How many bytes must memcpy copy for "cat"?
- Who frees the heap block returned by copyString?
Answers
- The bytes can be correct while the pointer refers to storage that free cannot release.
- Lost, if result held its only copy; assignment did not release the allocation.
- Four: three characters and '\0'.
- The caller, after its last use of the returned string.