- How
malloc(n * sizeof(int))creates ann-element array whose size is chosen at runtime - Why indexing (
arr[i]) and pointer arithmetic (*(arr + i)) work identically on a heap-allocated array - How to check for
NULLand guard against integer overflow in the size computation - How to free the block and why
free(arr)is still correct even though you've been moving the pointer - Why
malloc'd memory is uninitialized and howcallocdiffers
How Heap-Allocated Arrays Work
A stack array like int arr[10]; has a fixed size that must be known at compile time — or, in C99 and later, at the point of declaration, which still requires the value to be available when the array is created. If the size isn't known until the program is running (e.g., the user enters it), you can't use a stack array for it in standard C. This is the canonical reason for dynamic allocation: to create an array whose size is decided at runtime.
The mechanism is simple: malloc(n * sizeof(int)) requests n * sizeof(int) bytes on the heap, and returns a pointer to the first byte. Because the block is contiguous and typed as int *, you can index it exactly like a stack array: arr[i] accesses the i-th element, and arr + i points at it. This is not a coincidence — C defines arr[i] as *(arr + i), so pointer arithmetic and array indexing are literally the same operation. There's no "heap array" type in C; a dynamic array is just a pointer to a heap block, used with the same indexing syntax.
The heap block has allocated storage duration: it exists from the moment malloc returns until free is called. That means it survives the end of the function that created it, unlike a stack array. It also means you're responsible for releasing it — the runtime won't do it for you. Forgetting free leaks the block; using the pointer after free is undefined behaviour. The discipline is: every successful malloc gets exactly one free, with no use of the pointer in between that could outlive the block.
💡 In one line: int *arr = malloc(n * sizeof(int)); gives you an n-element array you can index as arr[i]; free it with free(arr) when done.
The Three Steps of Dynamic Array Allocation
| Step | Operation | Effect |
|---|---|---|
| 1. Allocate | int *arr = malloc((size_t)n * sizeof(int)); | A contiguous block of n ints on the heap |
| 2. Check and use | if (arr == NULL) { ... } then arr[i] = ... | NULL → allocation failed; otherwise arr[0] through arr[n-1] are valid |
| 3. Release | free(arr); arr = NULL; | The block returns to the allocator; the pointer is safely nulled |
The size expression (size_t)n * sizeof(int) has a subtle but important property. If n is an int and sizeof(int) is a size_t (which it is, in standard C), then the multiplication is done in size_t arithmetic — because the usual arithmetic conversions promote n to size_t. But if n is very large (close to INT_MAX) and sizeof(int) is 4, then n * 4 in size_t (unsigned 64-bit) is fine; but if n were an int and sizeof(int) were somehow also int (on some exotic platform), the multiplication could overflow. Casting n to size_t before multiplying makes the intent explicit and avoids any signed/unsigned surprises. In C11 and later, you can also use malloc(n * sizeof(int)) and rely on the conversions — but being explicit is the safer habit.
The free(arr) call must be given the same pointer value that malloc returned. It's fine to have moved arr around while using it (e.g., arr++ to walk through the elements), as long as you restore the original pointer before calling free. In the program, arr is never reassigned, so free(arr) is correct. If you had int *p = arr; and only used p for the walk, you would still call free(arr) at the end — the original pointer is what free needs.
Complete C Program
Program: allocate an n-element int array on the heap, fill it, print it, and free it
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main(void) {
int n;
printf("How many integers? ");
if (scanf("%d", &n) != 1 || n < 0) {
fprintf(stderr, "Invalid size.\n");
return 1;
}
/* Guard against size overflow on the multiply. */
if ((size_t)n > SIZE_MAX / sizeof(int)) {
fprintf(stderr, "Size too large for this platform.\n");
return 1;
}
/* 1. Allocate n ints on the heap. */
int *arr = malloc((size_t)n * sizeof(int));
if (arr == NULL) {
fprintf(stderr, "malloc failed: out of memory\n");
return 1;
}
/* 2. Fill and print through the pointer. */
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
if (scanf("%d", &arr[i]) != 1) {
fprintf(stderr, "Invalid input.\n");
free(arr);
return 1;
}
}
printf("You entered:");
for (int i = 0; i < n; i++) {
printf(" %d", arr[i]);
}
printf("\n");
/* Sum and average, computed by walking the array with a pointer. */
long sum = 0;
int *p = arr;
int *end = arr + n;
while (p < end) {
sum += *p;
p++;
}
printf("Sum = %ld, average = %.2f\n", sum, n > 0 ? (double)sum / n : 0.0);
/* 3. Release the memory. */
free(arr);
arr = NULL;
return 0;
}
Program Output
How many integers? 5
Enter 5 integers:
10 20 30 40 50
You entered: 10 20 30 40 50
Sum = 150, average = 30.00
A second run, with a different size chosen at runtime:
How many integers? 3
Enter 3 integers:
7 8 9
You entered: 7 8 9
Sum = 24, average = 8.00
In both runs, the size is read from the user and used to size the heap block — the program never had to know the array size at compile time, which is the whole point of dynamic allocation. The array is filled with scanf (through arr[i]), printed in the same order, and then walked with a pointer (p) to compute the sum. The two access patterns — indexing and pointer arithmetic — work identically on the same block, as the C standard guarantees.
Step-by-Step Explanation
Let's walk through the allocation, use, and release in detail.
1. Reading the size at runtime
int n; and scanf("%d", &n); let the user choose the array size after the program starts. This is the key difference from a stack array, whose size must be a constant expression. (C99's variable-length arrays offer a partial alternative, but they're not universally supported and can't survive the end of their block.) Here, n is just an ordinary local variable — the size is decided at runtime.
2. The overflow guard
if ((size_t)n > SIZE_MAX / sizeof(int)) catches the case where n * sizeof(int) would overflow size_t. This matters for very large n: if n is, say, SIZE_MAX / 4 + 1 and sizeof(int) = 4, then n * sizeof(int) would wrap around to a small value, and malloc would allocate a small block — but the program would then write n elements through it, overflowing the buffer. The guard rejects such inputs before any allocation happens. For ordinary use (a few thousand ints), it never triggers, but it's the correct thing to do for robust code.
3. The malloc call
malloc((size_t)n * sizeof(int)) requests exactly enough bytes to hold n ints. The (size_t) cast on n makes the multiplication unsigned and wide, matching sizeof's type. The returned void * is assigned to int *arr — the implicit conversion in C is fine, and if you later change arr's type, the assignment will still compile without a cast that could hide a size mismatch. The block is not zero-initialized; you must fill it before reading.
4. The NULL check
if (arr == NULL) guards against allocation failure. For small n, this almost never happens, but for large n it's the realistic failure mode: the process has a per-allocation and total heap limit, and requesting gigabytes will fail. A NULL check lets the program exit gracefully with an error message rather than dereferencing NULL and crashing. It's a habit that pays off exactly when the program is under memory pressure — the worst time to have a cryptic crash.
5. Indexing the heap array
arr[i] works exactly like it does for a stack array. The compiler translates it to *(arr + i) — pointer arithmetic followed by dereference. Because the block is contiguous, arr + i is a valid pointer to the i-th int, and *(arr + i) reads or writes that int. This is why you can use the same syntax for stack and heap arrays; the underlying operation is identical. The bounds are the only thing that matters: for i in 0..n-1, arr[i] is valid; for i < 0 or i >= n, it's undefined behaviour.
6. Walking with a pointer
int *p = arr; and int *end = arr + n; set up a half-open range. while (p < end) { sum += *p; p++; } visits every element once. This is the same idiom used throughout C (in memcpy, qsort, the standard iterators), and it works on heap arrays for the same reason it works on stack arrays: pointers are pointers. The end pointer is one past the last element — legal to form, never to dereference. When p reaches end, the loop exits and sum holds the total.
7. The n == 0 edge case
If the user enters 0, malloc(0) is called. The C standard says malloc(0) may return either NULL or a unique pointer; both are valid, and both must be treated as "a zero-element block." In the program, the fill and print loops don't run (their bounds are i < 0, false from the start), the sum is 0, and the average computation is guarded with n > 0 ? ... : 0.0 to avoid dividing by zero. The program handles 0 correctly without special-casing the allocation itself — it just treats the returned pointer as a valid zero-length array. This is the robust behaviour, and it's worth knowing that "zero elements" is a perfectly meaningful array, not an error.
8. Freeing the block
free(arr) releases the entire block. The pointer must be the same one malloc returned — if you had reassigned arr elsewhere (e.g., arr++ to walk it), you'd need to restore the original before freeing. In this program arr is never moved, so free(arr) is correct. After free(arr); arr = NULL;, the pointer is safely nulled — a subsequent accidental dereference crashes cleanly instead of silently reading freed memory (use-after-free), which is far harder to debug.
9. Why calloc might be useful
malloc returns uninitialized memory; if you read arr[i] before writing it, you get whatever garbage was there. For most programs you fill the array first (as here), so malloc is fine. But if you need zero-initialized memory — for a counter array, a histogram, or a lookup table — calloc(n, sizeof(int)) is the better choice: it allocates n * sizeof(int) bytes and zeroes them before returning. The cost is one pass over the block, which for n elements is O(n) — often worth it for the guarantee.
10. Why realloc matters
If the array needs to grow or shrink after allocation, realloc(arr, new_size) resizes it. It may return the same pointer (if the allocator has room to extend in place) or a new pointer (if it must move the block). Either way, you must capture the return value: int *new_arr = realloc(arr, new_size); if (new_arr) arr = new_arr; — because realloc returns NULL on failure and leaves arr untouched, and because it may have moved the block. This is a natural extension of the malloc/free pattern, and it's what dynamic arrays (like std::vector in C++) do under the hood.
11. The difference from a variable-length array
C99 allows "variable-length arrays" (VLAs) where the size is an expression: int arr[n]; inside a function. VLAs are allocated on the stack like regular arrays, and they're freed automatically when the block exits. For small n, they're convenient. But they have limitations: no way to check allocation failure (if the stack can't grow, the program crashes), no way to return them from a function, and no way to resize them. Heap allocation with malloc is more flexible: it can fail gracefully, can outlive the function, and can be resized. For production code, heap allocation is the more robust choice; VLAs are useful for small, short-lived arrays where the size is bounded and failure is impossible.
12. Complexity
malloc and free are O(1) amortized for small blocks. The fill loop, print loop, and walk are each O(n). Total time is O(n) for the array operations, plus O(1) for the allocation bookkeeping. Space is O(n) for the block itself, plus O(1) for the pointer variables. This is optimal for a dynamic array — the memory used is exactly what the program needs, and each element is touched a constant number of times.
🎯 Remember this: malloc(n * sizeof(int)) gives you a runtime-sized array you can index as arr[i] and walk as *(arr + i). Check for NULL, guard against overflow, fill before reading, and always free — then set arr = NULL. For zero-initialized arrays use calloc; for resize, use realloc.
Frequently Asked Questions
1. Why can't I just use int arr[n]; with a runtime n?
In C99 and later, you can — those are variable-length arrays (VLAs), and they're allocated on the stack. But they have limitations: (a) you can't detect allocation failure — if the stack can't accommodate n ints, the program crashes; (b) the array is destroyed when its block exits, so you can't return it from a function; (c) you can't resize it. Heap allocation with malloc solves all three: it can fail gracefully (returns NULL), it survives the function (until free), and it can be resized with realloc. For small, short-lived arrays with bounded size, VLAs are fine; for anything else, use the heap.
2. Why does arr[i] work on a heap-allocated array?
Because C defines arr[i] as *(arr + i) — pointer arithmetic followed by dereference. For this to work, arr must be a pointer to a contiguous block of ints, which is exactly what malloc(n * sizeof(int)) returns. The heap block is contiguous, so arr + i points at the i-th int, and *(arr + i) reads or writes it. Stack arrays and heap arrays are accessed identically because they're both "a pointer to a contiguous block" — the only difference is where the block lives and when it's destroyed.
3. Why is the multiplication cast to size_t?
Because n is a signed int, while sizeof(int) is an unsigned size_t. In the multiplication n * sizeof(int), the usual arithmetic conversions promote n to size_t anyway — so the cast is technically redundant on most platforms. But writing (size_t)n * sizeof(int) makes the intent explicit and prevents any sign-extension surprise on platforms where the types behave differently. It's a defensive habit; the compiler will generate the same code. The related guard n > SIZE_MAX / sizeof(int) prevents overflow if n is very large — without it, the multiplication could wrap and malloc could return a block smaller than the program expects, leading to a buffer overflow.
4. What happens if I forget to free the array?
The memory remains allocated until the program exits. For a small array in main that never grows, this is harmless — the OS reclaims everything when the process ends. But in a loop, in a library function called many times, or in a long-running program, the leaked blocks accumulate and can exhaust the heap, causing future malloc calls to fail. For programs that run for a long time (servers, embedded devices), leaks are a serious bug. Get in the habit of pairing every malloc with a free on all exit paths — including error paths, as the program does with free(arr) before returning 1 when scanf fails.
5. Can I use realloc to grow the array later?
Yes. realloc(arr, new_size) resizes the block, preserving the existing contents up to the smaller of the old and new sizes. If it can, it extends in place (returns the same pointer); otherwise it allocates a new block, copies the contents, frees the old one, and returns the new pointer. Either way, capture the return value: int *tmp = realloc(arr, new_size); if (tmp == NULL) { /* handle error, arr is still valid */ } else { arr = tmp; }. Don't do arr = realloc(arr, ...) directly — if realloc fails and returns NULL, you'd lose the original pointer and leak the original block.
6. What is the time and space complexity?
malloc(n * sizeof(int)) and free(arr) are O(1) amortized for typical allocations. The fill, print, and walk loops are each O(n) — every element is visited a constant number of times. So total time is O(n), and space is O(n) for the array itself plus O(1) for pointers. This is optimal for a dynamic array — you use exactly the memory you request, and you do O(n) work to populate and consume it.
💡 Tip: Once this works, extend it to a dynamically allocated 2D array (an array of pointers, where each pointer is a row of malloc'd ints), or to a string (assignment #13 — allocate len + 1 bytes and copy the characters). Both are natural extensions of the same "malloc a block, use it, free it" pattern, with the wrinkle that a 2D array requires freeing each row and then the array of pointers. That's the next step in thinking about heap-allocated data structures.