Open-Source C Programming • Foundational • Estimated study time: 45 minutes.
A monitoring program might receive four temperature samples today and thousands tomorrow. A fixed-size array is not always sufficient. Dynamic allocation allows a C program to obtain storage at runtime, extend it when necessary and return it when the data is no longer needed. This lesson follows C structures and pointer parameters.
Learning objectives
By the end, you should be able to distinguish automatic from allocated storage; calculate the bytes required by an array; use malloc, calloc, realloc and free; preserve the original allocation on a failed resize; and prevent arithmetic overflow, invalid access and memory leaks.
Four allocation functions
malloc(bytes) obtains uninitialized storage. calloc(count, size) obtains storage with all bits zero. realloc(pointer, bytes) changes the size of an existing allocation and may move it; on failure for a nonzero size, the original allocation remains valid. free(pointer) releases storage; free(NULL) does nothing. These interfaces are declared in <stdlib.h>. Review the Linux malloc(3) manual for API details and platform-specific behavior.
Harvard CS50: Dynamic Memory Allocation, an instructional short introducing runtime allocation. Course materials and alternate video player.
Capacity and byte arithmetic
B = n × s, where B is the required number of bytes, n is the element count, and s = sizeof(element) is the size of one element in bytes. On a system with four-byte int objects, four elements require 16 bytes; eight require 32 bytes. Use sizeof *pointer rather than assuming that an int always occupies four bytes. Before multiplying, reject n greater than SIZE_MAX / s. This is the allocation-size safeguard explained in the SEI CERT MEM35-C rule. A program must also track the number of initialized elements separately from its capacity.
Worked example: growing a telemetry buffer
The following example builds on array indexing and bounds, pointer parameters and buffer capacity. Four synthetic readings are preserved while capacity grows to eight. The new elements are explicitly initialized.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
int main(void) {
size_t n = 4, next = 8;
int *samples;
if (n == 0 || n > SIZE_MAX / sizeof *samples) return EXIT_FAILURE;
samples = malloc(n * sizeof *samples);
if (!samples) return EXIT_FAILURE;
for (size_t i = 0; i < n; ++i) samples[i] = (int)(i + 1);
if (next <= n || next > SIZE_MAX / sizeof *samples) {
free(samples); return EXIT_FAILURE;
}
int *tmp = realloc(samples, next * sizeof *samples);
if (!tmp) { free(samples); return EXIT_FAILURE; }
samples = tmp;
for (size_t i = n; i < next; ++i) samples[i] = 0;
assert(samples[0] == 1 && samples[3] == 4 && samples[7] == 0);
printf("capacity=%zu, first=%d, last=%d\n", next, samples[0], samples[next-1]);
free(samples);
samples = NULL;
return EXIT_SUCCESS;
}
Compile locally with GCC or Clang and run the executable:
cc -std=c17 -Wall -Wextra -Wpedantic -Werror -fsanitize=address,undefined telemetry.c -o telemetry
./telemetry
The exact example was compiled and executed with those options; its assertions passed and output was:
capacity=8, first=1, last=0
Why a temporary pointer matters
Assigning realloc directly to samples can lose the only reference to the old allocation if the operation fails. Instead, assign to tmp, test tmp for NULL and only then update samples. If the resize succeeds, any previous alias into that storage must no longer be used. This applies even when the returned address happens to look unchanged.
Community discussion of realloc and dangling pointers; use the documented C behavior, not forum advice alone, as your authority.
Operational safety
A leak can gradually exhaust a long-running monitoring service. A dangling pointer or out-of-bounds write can corrupt records or crash a process. Do not free automatic storage, free the same allocation twice, read uninitialized bytes, or use a pointer after its allocation is released. Avoid zero-size allocations and zero-size realloc in this exercise because their semantics differ across C revisions. SEI CERT MEM34-C describes valid release operations. Use synthetic data in a sandbox, not production infrastructure.
Exercises and answer key
A. Calculate the allocation size for 128 eight-byte readings. B. What happens to the original allocation if realloc returns NULL for a nonzero request? C. Does malloc initialize its storage? D. Why test n > SIZE_MAX / sizeof *samples? E. What happens if an old alias is dereferenced after successful realloc? F. How many elements may be read from the worked example after it initializes the new slots?
Answers: A. 1,024 bytes. B. It remains allocated and can still be released or used. C. No. D. To avoid unsigned multiplication wrapping into a smaller allocation. E. The old alias is invalid; using it can cause undefined behavior. F. Eight elements, indexed zero through seven.
Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.
BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.
Leave a Reply