Dynamic memory and ownership
Connect allocation, initialization, size checks, replacement, and release to a deliberate ownership contract.
In this chapter9 sections
Sometimes a program learns the required storage size only while it is running. Allocation requests that storage; ownership tells us who must release it. We will follow both the successful path and what happens when a request fails.
1. Allocation controls a different lifetime
malloc, calloc, realloc, and free are declared in <stdlib.h>. Their rules control allocated storage. A local pointer to that storage can disappear without ending the allocation; an allocated object can be freed while a pointer object still exists. The pointer and the allocation are not one shared lifetime.
- Request storage
- Check result
- Initialize and use
- Release once
int *value = malloc(sizeof *value);
if (value == NULL) {
return EXIT_FAILURE;
}
*value = 4;
assert(*value == 4);
free(value);
value = NULL;
For this non-VLA target type, sizeof *value determines the required size without dereferencing the pointer. Check the result before accessing the allocation. In C, the returned void * converts to an appropriate object pointer without a cast. malloc does not initialize the allocated bytes; the assignment supplies a usable int value here.
2. Compute a size without losing its meaning
SIZE_MAX is provided by <stdint.h>; include it for this size-limit check. The fragments also use assert from <assert.h> to state checks on these initialized values.
size_t count = 3;
int *values = NULL;
if (count == 0 || count > SIZE_MAX / sizeof *values) {
return EXIT_FAILURE;
}
values = malloc(count * sizeof *values);
if (values == NULL) {
return EXIT_FAILURE;
}
values[0] = 4;
values[1] = 5;
values[2] = 6;
assert(values[2] == 6);
free(values);
The interface deliberately rejects a zero count. The division check happens before multiplication, preventing count * sizeof *values from wrapping in size_t. A wrapped small result could otherwise allocate too little space for the element count. sizeof *values uses the intended element type; sizeof values would give the pointer size instead.
A successful ordinary allocation provides alignment suitable for types with fundamental alignment requirements. Do not generalize that to every extended or specially aligned type. Also do not treat a cast as initialization: access must respect alignment and the effective-type rules for storage without a declared type. This lesson uses ordinary integers written through correctly typed pointers.
3. calloc promises zero bits
int *values = calloc(3, sizeof *values);
if (values == NULL) {
return EXIT_FAILURE;
}
assert(values[0] == 0);
assert(values[2] == 0);
free(values);
calloc takes an element count and element size separately and sets the allocated space’s bits to zero. For the integer objects in this example, that represents integer zero. It does not universally establish null pointer values or floating-point zero values in arbitrary allocated objects. Byte zeroing and language-level initialization are related but different operations.
4. realloc replaces an allocation on success
#include <assert.h>
#include <stdlib.h>
int main(void)
{
int *values = malloc(2 * sizeof *values);
if (values == NULL) {
return EXIT_FAILURE;
}
values[0] = 4;
values[1] = 5;
int *replacement = realloc(values, 3 * sizeof *values);
if (replacement == NULL) {
free(values);
return EXIT_FAILURE;
}
values = replacement;
values[2] = 6;
assert(values[0] == 4 && values[1] == 5);
assert(values[2] == 6);
free(values);
return 0;
}
For a valid old allocation and a nonzero requested size, failure returns a null pointer and leaves the old allocation available. Keeping the result in a temporary preserves the owning pointer on failure. On success the old allocation is deallocated and the returned pointer designates the replacement, which may occupy the same apparent address. Stop using every old pointer into the old object; do not compare the old pointer with the result.
The existing contents are preserved up to the smaller of the old and new sizes. Newly added storage is not automatically initialized. The example assigns the new third element before reading it. After replacement, rebuild any needed interior pointers from the returned pointer and valid offsets, rather than carrying stale aliases forward.
5. Ownership is a contract you maintain
Ownership identifies which part of the program is responsible for release. A borrowed pointer may access the object only while the contract permits; a raw C pointer does not record or enforce that distinction. Copying an owner’s pointer does not create two allocations or authorize freeing both copies. One allocation must be released at most once through a valid deallocation path.
free(NULL) does nothing. Otherwise pass a valid allocation pointer accepted by the deallocator, not an interior pointer, an automatic array, a string literal, or an already released value. Freeing need not immediately return physical pages to an operating system. A leak is a management failure involving unreleased storage, rather than a promise that a particular heap diagram grows in one direction.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 6.2.4, 6.5p6–p7, 7.22.3 (stable allocation rules). These stable rules support the C17 baseline; this draft is not the final ISO publication.
- WG14 N3096 — public C23 draft: 7.24.3.7, especially the separate null and non-null first-argument branches. Draft wording; consult implementation support separately.
WG14 N2438: documents the C17 zero-size realloc wording and its ambiguity; it is a committee issue paper, not the final C23 rule.
Optional visual model: Resize and release an allocation
Resize and release an allocation
VISUAL MODEL
Explore both outcomes of a positive-size realloc request. Follow the owning pointer and the temporary result.
Include <stdlib.h> before the function definition. Run this fragment inside a void function. Assume the first malloc succeeds. The realloc outcome is a teaching scenario, not a real allocator control.
int *p = malloc(2 * sizeof *p);if (p == NULL) return;p[0] = 4; p[1] = 8;int *tmp = realloc(p, 3 * sizeof *p);if (tmp != NULL) {p = tmp;p[2] = 12;}free(p);p = NULL; tmp = NULL;
p—Initializer not reachedtmp—Initializer not reachedB (allocation)—No allocation yetNo allocation has been requested yet. Neither pointer initializer has been reached.
A and B are logical allocation labels, not addresses. ? means a value must not be read. Successful realloc ends the old allocation’s lifetime even if an implementation reuses an address. Only positive sizes are used.
Read the complete trace
- No allocation has been requested yet. Neither pointer initializer has been reached.
- malloc succeeds and p owns allocation A, with room for two int objects. Their values have not been initialized.
- The two int values become 4 and 8. The requested allocation size was expressed using sizeof *p.
- realloc succeeds. tmp refers to allocation B; the first two values are preserved. The old allocation has ended, so the old value in p must not be read.
- p receives tmp, replacing its unusable old value without reading it. p now owns B; tmp is an alias.
- p[2] receives 12. All three int values in B are now initialized.
- free releases the live allocation once. Pointer values that referred to it must not be read afterward. No value is read from released storage.
- Both pointer objects are assigned NULL. This replaces old values; it does not release any additional allocation.
Before you move on
- Allocation requests a region whose size is chosen while the program runs.
- The program must validate size arithmetic, handle failure, and establish usable values.
- Ownership and borrowing rules determine release and the validity of aliases.
Keep these ideas separate
- Allocated bytes / Initialised values
- Obtaining storage does not automatically initialise every intended typed value or establish every access contract.
How would you replace an allocation while keeping the original pointer available if resizing fails?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- The old allocation has always been freed.
For this positive-size failure, the old allocation is not deallocated.
- The new third element is ready to use.
A failed growth request did not create that extra space.
- The original allocation, reachable through the preserved owning pointer.
✓ Correct reasoning. Use a temporary result so a failed call does not overwrite the pointer needed to access and release the original allocation.
C17
Quick reference from the earlier edition
Retained for existing section links and saved passages. Read the expanded explanation above for the connected learning sequence.
Allocated storage, often called heap memory, is obtained through <stdlib.h> functions and remains allocated until released or replaced according to their rules. Automatic objects instead have lifetimes managed by their scopes. These are language lifetime categories, not a requirement for particular physical stack and heap regions.
| Function | Behavior |
|---|---|
malloc(size) |
Allocates size bytes with indeterminate contents; check for NULL. Avoid zero-size requests. |
calloc(n, size) |
Allocates space for n elements of size bytes each and sets all bits to zero. This does not guarantee a null-pointer or floating-zero representation. |
realloc(ptr, size) |
For nonzero size, resizes an allocation; on failure NULL leaves the old allocation valid. On success the old allocation is invalidated, even if the address is unchanged. |
free(ptr) |
Releases a valid, not-yet-freed allocation; free(NULL) does nothing. |
Common Mistakes
- Memory leaks — allocated storage is retained after it is no longer needed; losing the last usable pointer is a common cause. Reclaiming process storage on exit is operating-system behavior, not a C language guarantee.
- Dangling pointer / use-after-free — accessing memory through a pointer after that memory has already been freed.
- Double free: Freeing the same allocation twice, or freeing an interior/unrelated pointer, is undefined behavior. The implementation does not promise a particular crash or allocator diagnostic.
- Losing the original pointer on
reallocfailure — writingptr = realloc(ptr, newSize);overwritesptrwithNULLon failure and silently leaks the original block. The safe pattern uses a temporary variable:void *tmp = realloc(ptr, newSize); if (tmp) ptr = tmp;.
Check every allocation result before use, and check for size overflow before expressions such as n * sizeof *p. A successful realloc replaces the old allocation; a failed nonzero-size request leaves it available, so assign through a temporary pointer. Avoid realloc(p, 0) for a valid non-null allocation pointer p: C17 has implementation-defined behavior that can release the old block, while C23 makes this case undefined behavior. realloc(NULL, size) follows malloc(size), including its zero-size rules. Handle a requested size of zero explicitly with free(p). Release allocations when ownership ends, without using stale aliases; Do not separately free the old block after a successful realloc. Tools can help detect leaks and invalid accesses.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.