CSSE 132 Mini-reading · Task 14
Heap and Dynamic Memory Allocation in 10 Minutes
Review how to request memory, use it across function calls, and release it when you finish.
Why This Matters
A function sometimes needs to create an array whose size becomes known while the program runs. Sometimes its caller needs to keep using that array after the function returns. Heap allocation lets you control that storage's lifetime, but it also makes you responsible for releasing it. Worksheet 14 practices that responsibility.
Core Idea
The heap provides memory you request while your program runs. The allocator finds a contiguous block of the requested number of bytes and returns its starting address. It keeps track of allocations so it can avoid handing out space that is already in use.
Local storage on the stack
A local array such as char text[3] belongs to that function call. Its lifetime ends when the function returns. Returning its address does not keep the array alive.
Allocated storage on the heap
A block obtained with malloc remains allocated after the allocating function returns. Another function can use it through a pointer until the program calls free on that allocation.
Runtime size and lifetime are different ideas: C also permits local arrays with runtime sizes in some environments. Heap allocation is especially useful when storage must outlive the function call that created it.
Include <stdlib.h> for malloc and free. malloc takes a byte count (of type size_t) and returns a pointer, or NULL if allocation fails. It does not initialize the contents. Check the result before accessing the block.
Worked Examples
Example 1: A string that survives a return
The lecture's local-array example returns an address whose storage has expired. Here is a heap version with the same three characters:
#include <stdlib.h>
char* create_string(void) {
char* text = malloc(3 * sizeof(char));
if (text == NULL) {
return NULL;
}
text[0] = 'H';
text[1] = 'i';
text[2] = '\0';
return text;
}
Three bytes hold two letters and the terminating null character. The local pointer variable text goes away on return, but the allocated bytes remain. Returning the pointer value gives the caller an address it can keep using.
char* message = create_string();
if (message != NULL) {
printf("%s\n", message); // include <stdio.h>
free(message);
}
The caller releases the allocation after printing. The string must not be read again after free.
Example 2: Allocate and initialize an array
For six integers, calculate the number of bytes before allocating:
6 entries × sizeof(int)
= 6 × 4 bytes in our ARM64 environment
= 24 bytes
int* create_values(void) {
int* values = malloc(6 * sizeof(int));
if (values == NULL) {
return NULL;
}
for (int i = 0; i < 6; i++) {
values[i] = 2 * i;
}
return values;
}
The array contains 0, 2, 4, 6, 8, 10. Indexing works because values points to the first integer and C scales each index by the element size. The valid indices are 0 through 5. The caller must track the count separately and eventually call free on the returned pointer.
Example 3: What does sizeof measure?
char* bytes = malloc(40);
char letters[12];
In our 64-bit ARM64 environment, sizeof(bytes) is 8: it measures the pointer variable. It does not report the 40 allocated bytes. sizeof(letters) is 12 here because letters is an actual array in this scope.
Use sizeof(int) or sizeof(struct db_entry) to calculate storage per entry. Worksheet 14's warning is a reminder to track array lengths yourself, especially when working through pointers. sizeof does not follow a pointer to discover the allocation's size.
Example 4: Follow the addresses to find a leak
Assume both allocations succeed:
char* buffer = malloc(40); // buffer holds address A
buffer = malloc(60); // buffer now holds address B
free(buffer); // releases the block at B
The second assignment overwrites the only saved address of block A. Its 40 bytes remain allocated, but the program has lost the pointer needed to release them. This is a memory leak. Releasing B does not release A.
For a loop, list each allocation's size and record which address the final pointer holds. Count the earlier blocks that remain allocated. If the blocks contain structs, first find the size of one struct, then multiply by the number of entries.
Example 5: Worksheet 14's allocation loop
Here is the loop from Worksheet 14. For this exercise, calculate the struct size by adding its fields: an 8-byte pointer plus a 4-byte integer gives a 12-byte entry. Assume the positive-size allocations succeed.
#include <stdio.h>
#include <stdlib.h>
struct test {
char* name;
int value;
};
int main() {
struct test* tp;
for (int i = 0; i < 4; i++) {
tp = malloc(i * sizeof(struct test));
}
free(tp);
return 0;
}
Step 1: Calculate each request. Multiply the loop value by the 12-byte entry size used in this exercise.
| Iteration | Bytes requested | What happens to the previous allocation? |
|---|---|---|
i = 0 | 0 × 12 = 0 | No positive-size block yet. |
i = 1 | 1 × 12 = 12 | The previous pointer is overwritten. |
i = 2 | 2 × 12 = 24 | The address of the 12-byte block is lost. |
i = 3 | 3 × 12 = 36 | The address of the 24-byte block is lost. |
Step 2: Apply the free. When the loop ends, tp holds the address of the final 36-byte block. free(tp) releases that block only. It does not release earlier blocks whose addresses were overwritten.
Step 3: Add the unreleased bytes.
Leaked bytes = 12 + 24 = 36 bytes
The loop requests 0 + 12 + 24 + 36 = 72 bytes in this exercise's size model and releases the final 36 bytes. The first request, malloc(0), may return NULL or a pointer that can be freed; it contributes zero requested bytes to this calculation. Count requested bytes, excluding allocator bookkeeping.
To avoid losing a block, release it before overwriting its only pointer, or keep its address if you still need it. The name field stores a pointer; this loop does not allocate a separate string.
Common Mistakes
Requesting entries instead of bytes
malloc(6) requests six bytes. Six integers need 6 * sizeof(int) bytes.
Assuming fresh memory contains zeros
malloc leaves the contents uninitialized. Assign values before reading them, and check for NULL before writing.
Freeing the wrong address
Pass the original allocation address to free. Do not free a local array or an address of an element inside a block. Release each allocation once.
Using a pointer after free
free releases the block but does not automatically change your pointer. Assigning NULL afterward can help avoid reuse through that variable, but other pointers to the same block are still invalid.
Quick Reference
| Task | Rule |
|---|---|
| Declare the functions | #include <stdlib.h> |
| Request an array | int* p = malloc(count * sizeof(int)); |
| Check success | Handle p == NULL before accessing the block. |
| Initialize entries | Write each entry before reading it. |
| Keep the length | Store or pass the entry count separately. |
| Release the block | free(p); after the last use. |
| Heap lifetime | Continues across function returns until release. |
Check Yourself
Try these before opening the answers. These examples use different values from Worksheet 14.
- A function returns a pointer to its local
int data[4]. Why is using that pointer afterward invalid? - How many bytes do seven integers need when
sizeof(int)is 4? Write the allocation expression. - For
int* p = malloc(28), what issizeof(p)in our ARM64 environment? - Assuming success, a pointer receives allocations of 20, 30, then 50 bytes. Only the final block is freed. How many bytes leak?
- A successful
mallocis followed immediately by reading the first entry. What step is missing?
Answers
Show the answers
- The local array's lifetime ended when the function returned. Copying its address does not extend that lifetime.
- 28 bytes:
malloc(7 * sizeof(int)). The expression converts an entry count to a byte count. - 8 bytes.
pis a pointer, regardless of the size of the allocated block. - 50 bytes: the earlier 20-byte and 30-byte blocks. Freeing the final 50-byte block releases only that block.
- Initialize the entry. Successful allocation provides storage, but does not supply initial values.
Next Step
Complete Worksheet 14. For each code trace, keep track of the pointer's value, the allocated block's size, and the point where that block is released.