Dynamic Memory Allocation: Size, Use, and Release
Dynamic memory allocation requests storage while a program runs and lets the program control when that storage is released. In C, you use it when an array's required size becomes known during execution or its storage must outlive the function that creates it. The central responsibility is to track both the allocated block and the code responsible for releasing it.
Request the right number of bytes
The allocation functions are declared in stdlib.h. For an array, distinguish the number of elements from the number of bytes requested:
Here, B is the requested byte count, n is the element count, and s is the size of one element in bytes. In C, write the size calculation as n * sizeof *p when p will point to the elements. This expression follows the element type automatically; sizeof p measures the pointer itself.
Example: If an array needs 25 integers and sizeof(int) is 4 bytes on the target system, request 25(4)=100 bytes. The pointer's own size does not determine this request.
The count commonly has type size_t. Before multiplying a runtime count, check that n <= SIZE_MAX / sizeof *p, with SIZE_MAX available through stdint.h. Otherwise, unsigned multiplication can wrap and produce an allocation smaller than intended. Handle a zero count separately; the patterns here assume positive counts.
Choose allocation and initialization deliberately
These functions have different jobs. In the table, bytes, n, and s are positive, valid sizes.
Function | Main purpose | Important consequence |
|---|---|---|
malloc(bytes) | Request a new block | Its contents are not initialized |
calloc(n, s) | Request storage for an array | Every allocated bit is initially zero |
realloc(p, bytes) | Replace a block with a resized allocation | It may move the allocation |
free(p) | Release an allocation | The block is no longer available for access |
An allocation request can fail and return NULL. Check the result before accessing any element. Successful malloc does not supply meaningful initial values, so write each element before reading it. For integer arrays, calloc supplies initial values of zero; its all-bits-zero guarantee is not a general guarantee of floating-point zero or null pointer representations.
For example, this fragment belongs inside a function returning an integer status, with stdlib.h included:
size_t n = 25;
int *p = malloc(n * sizeof *p);
if (p == NULL) {
return 1;
}
for (size_t i = 0; i < n; ++i) {
p[i] = 0;
}
free(p);
p = NULL;Resize and finish safely
For a positive requested size, failed realloc returns NULL and leaves the original allocation unchanged. Store the result in a temporary pointer, check it, and update the owning pointer only after success. Assigning directly to the owner can lose the original address when resizing fails.
Successful resizing preserves the first min(old_bytes, new_bytes) bytes. Added storage is not initialized. Success also ends the old allocation's lifetime: use the returned pointer and rebuild any other pointers into the block, even if the returned address appears unchanged.
A memory leak occurs when allocated storage remains unreleased after the program loses the means to release it. Leaving a function does not automatically free its dynamically allocated blocks. A dangling pointer is a different problem: storage has already been released, but a pointer still refers to it.
Release each owned live allocation exactly once when it is no longer needed. Pass free the allocation's base pointer, not an interior address; passing NULL is harmless. Use free directly to release a block rather than requesting a zero-sized realloc.
What to remember
- Calculate element count times element size, checking for overflow.
- Check allocation success and initialize values before reading them.
- Resize through a temporary pointer and use the returned pointer after success.
- Track responsibility for release across every exit path.
Example: Growing a sensor sample buffer
A C sensor logger owns an array through double *samples. Its capacity, the number of elements the allocation can hold, is currently 12. All 12 elements have been initialized. On this system, sizeof(double) is 8 bytes. The logger must grow the capacity to 20 elements.
Assume the initial allocation succeeded, both requested byte counts are representable, and the required headers are included. Ignore allocator overhead. The code continuation will run inside a function returning an integer status, with capacity already set to 12.
a) Calculate the requested size of the current allocation in bytes.
Multiply the number of elements by the size of one element. Each element occupies ________, and the current allocation holds 12 elements.
The current allocation's requested size is 96 bytes. This calculation measures the array storage, not the pointer variable or allocator overhead.
b) Calculate the byte count to pass to realloc and the number of added elements that need initialization after successful growth.
realloc takes the total new size, rather than the number of additional bytes. Therefore,
The number of added elements is 20−12, which is 8 elements. Those elements occupy 8(8)=64 bytes. The original prefix contains ________ and is preserved after successful growth.
The resize request is 160 bytes, and 8 added elements need initialization. Passing only the 64-byte increase would request a smaller total allocation and discard part of the original array.
c) Write a continuation that attempts the resize, initializes each added element to 0.0 after success, and releases the owned allocation before returning. Return 0 after success and 1 after failure.
First, keep samples unchanged while checking the resize result. On failure, the original allocation remains allocated. This function is abandoning its work on failure, so it releases that original allocation before returning.
size_t target = 20;
double *tmp = realloc(samples, target * sizeof *samples);
if (tmp == NULL) {
free(samples);
samples = NULL;
return 1;
}
samples = tmp;
for (size_t i = capacity; i < target; ++i) {
samples[i] = 0.0;
}
capacity = target;
free(samples);
samples = NULL;
return 0;After success, samples receives the returned pointer before the program accesses the resized array. The loop initializes indices 12 through 19, covering all eight added elements while preserving the original values. Updating capacity afterward records the new limit.
Finally, the success path releases the resized allocation. The failure path releases the unchanged original allocation. Thus, zero owned allocations remain at either return, with status 0 on success or 1 on failure.
A code reviewer has collected seven short descriptions of bugs found in C programs that use heap storage from malloc, calloc, realloc and free. Match each defect name to the program behaviour that produces it.
The address of a local array, or an address pointing partway into a heap block, is passed to the release function
The only pointer to a 4 KB block is reassigned to a new block before the first block is released
A function releases a block and returns its address, and the caller later reads values through that address
Two separate cleanup paths each release the same block, so the allocator receives that address twice
A pointer returned by an allocation call is dereferenced without first testing whether it is NULL
A loop stores a value at index n of an array that was allocated for exactly n elements
Elements of a block just obtained from malloc are summed before any element has been written
Unchecked allocation failure
Double free
Uninitialized read
Heap buffer overflow
Invalid free
Memory leak
Use after free
A C data logger executes the following statements. Both allocations succeed, sizeof(double) is 8 bytes, and no other pointer or stored address refers to either allocation. Ignore allocator overhead. How many allocated bytes remain leaked after the final statement? Answer in bytes, to zero decimal places.
double *p = malloc(18 * sizeof *p);
p = malloc(30 * sizeof *p);
free(p);
p = NULL;