Dynamic memory allocation
Dynamic memory allocation in C: heap vs stack, malloc/calloc/realloc/free, pointers, size_t, sizeof, dynamic arrays (1D/2D), error handling, leaks and dangling pointers, with runnable programs and exam-focused notes.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Engineers use dynamic memory allocation when the amount of data is not known at compile time, such as reading an unknown number of sensor values, variable-length messages, or growing data structures. It lets a C program request memory from the operating system at runtime, use it safely, and release it when done, so programs are efficient and robust.
Key ideas
- Stack: The stack is an area of memory used for function calls, parameters, return addresses, and automatic (non-static) local variables. It grows and shrinks automatically with function calls and returns. Lifetime of stack variables is limited to the block in which they are defined.
- Heap: The heap is an area of memory used for allocations that have lifetimes decided at runtime. The program explicitly requests and frees blocks of heap memory using allocation and deallocation functions.
- Dynamic memory allocation: Dynamic memory allocation is the process of obtaining and releasing memory during program execution using standard library functions. Exact statement: “In C, dynamic memory allocation is performed by functions declared in <stdlib.h> that return pointers to blocks of memory on the heap; the programmer is responsible for both checking for allocation failure and freeing allocated memory when it is no longer needed.”
- Pointer: A pointer is a variable that stores the address of another object. In dynamic memory allocation, allocation functions return a pointer to the first byte of the allocated block. A null pointer indicates no valid address.
- NULL: NULL is a macro for a null pointer constant. Exact statement: “A null pointer is guaranteed to compare unequal to any pointer to an object or function.” When allocation fails, functions return NULL.
- size_t: size_t is an unsigned integer type used to represent sizes of objects in bytes. It is defined in <stddef.h> (and also available via several other headers such as <stdio.h> and <stdlib.h>). It is the correct type for memory sizes and array indices.
- sizeof operator: sizeof yields the size, in bytes, of a type or of the type of an expression. It returns a value of type size_t. Using sizeof keeps code portable across platforms with different type sizes.
- malloc: malloc (memory allocation) requests a block of memory of a specified size in bytes and returns a pointer to the block, or NULL if the request fails. The content of the new block is indeterminate (uninitialized). Assumption: program has included <stdlib.h>.
- calloc: calloc (contiguous allocation) requests memory for an array of a given number of elements, each of a given size, initializes all bits to zero, and returns a pointer or NULL on failure. Note: calloc sets every byte to 0; for integer types this yields the value 0, but the C standard does not require that all-bits-zero represent a null pointer or 0.0 for floating-point on all platforms (though it does on most common IEEE 754 systems).
- realloc: realloc changes the size of a previously allocated block. Exact statement: “If successful, realloc returns a pointer to a block that contains the same data as the old block up to the lesser of the old and new sizes; the old block is freed. If it fails, it returns NULL and the original block is left untouched.” Assumption: The pointer passed to realloc was obtained from malloc/calloc/realloc and not already freed. Special cases: realloc(NULL, size) is equivalent to malloc(size); realloc(ptr, 0) frees ptr and returns NULL or a unique pointer that can be passed to free (implementation-defined which).
- free: free releases a block of memory previously allocated by malloc/calloc/realloc. Passing a null pointer to free has no effect. Using a pointer after free is undefined behavior.
- Undefined behavior (UB): A program has undefined behavior if the C standard imposes no requirements on its behavior. Examples here include dereferencing NULL, using a freed pointer, or writing beyond allocated bounds.
- Memory leak: A memory leak occurs when a program loses all pointers to an allocated block without freeing it, so the memory cannot be reclaimed until the process ends.
- Dangling pointer: A dangling pointer is a pointer that used to point to a valid object but the object’s lifetime has ended, e.g., after free. Using it is undefined behavior.
- Wild pointer: A wild pointer is an uninitialized pointer that points to an unpredictable location. It must be initialized before use, commonly to NULL or to a valid address returned by allocation.
- Fragmentation: Fragmentation is inefficient use of memory because free blocks are separated by allocated blocks, making it hard to satisfy large requests. External fragmentation occurs in the heap allocator; internal fragmentation occurs when an allocated block is larger than requested due to alignment and metadata.
- Alignment: Alignment is the requirement that objects be placed at addresses that are multiples of some value. Allocators return suitably aligned blocks for any object type. Assumption: hosted C implementation following the standard guarantees of alignment.
- Ownership and lifetime discipline: For every successful malloc/calloc/realloc that returns a non-NULL pointer p, there should be exactly one matching free(p) when the memory is no longer needed. After free, set the pointer to NULL to avoid accidental reuse.
- Casting malloc’s return in C: In C (not C++), it is not required to cast the void* return of malloc/calloc/realloc. Casting can hide a missing #include <stdlib.h> error. Exact recommendation: “Do not cast the result of malloc/calloc/realloc in C.”
- Bounded arithmetic for sizes: When computing sizes like n * sizeof(T), overflow of size_t leads to allocating less memory than intended and causes buffer overflows. Use checks before multiplication and prefer calloc(count, size) which may include internal overflow checks in some libraries.
- What to draw and label (exam diagram): Draw a vertical memory layout with labels from low to high addresses (explain that direction is conceptual and can vary by system). Top to bottom: Code (text), Static/Global (Data + BSS), Heap (grows upward), Free space, Stack (grows downward). Label arrows: “Heap growth” upward arrow; “Stack growth” downward arrow. Mark an allocated heap block with fields: “User data,” “Allocator metadata (conceptual, not directly accessible).” Show a pointer variable on the stack holding the address of the heap block.
Formulas
void *calloc(size_t count, size_t elem_size);— Allocates space for count elements each of size elem_size, initializes all bits to zero; returns pointer or NULL. Include <stdlib.h>.void *realloc(void *ptr, size_t new_size);— Resizes previously allocated block ptr to new_size bytes; returns new pointer or NULL. On failure, original ptr remains valid. Include <stdlib.h>.void free(void *ptr);— Frees memory previously allocated; does nothing if ptr is NULL. Include <stdlib.h>.sizeof(type)andsizeof expr— Yields size in bytes as size_t. Use for portable size calculations.NULL— Null pointer constant macro from <stddef.h> or <stdio.h>/<stdlib.h> by inclusion; used to signal failure or “no object”.- Pattern to allocate an array:
T *p = malloc(n * sizeof *p);— Allocates space for n objects of type T; usesizeof *pto track type automatically. - Pattern to allocate zero-initialized array:
T *p = calloc(n, sizeof *p); - Safe pattern to resize:
T *tmp = realloc(p, new_n * sizeof *p); if (tmp) { p = tmp; } else { /* handle failure, p unchanged */ } - Free and nullify:
free(p); p = NULL;
Worked examples
Example 1: Read N integers, compute average using malloc Program:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n;
if (scanf("%d", &n) != 1 || n <= 0) {
printf("Invalid input\n");
return 0;
}
int *a = malloc((size_t)n * sizeof *a);
if (a == NULL) {
printf("Allocation failed\n");
return 0;
}
long long sum = 0; // prevent overflow for large sums
for (int i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1) {
printf("Invalid input\n");
free(a);
return 0;
}
sum += a[i];
}
double avg = (n > 0) ? (double)sum / n : 0.0;
printf("Average = %.2f\n", avg);
free(a);
a = NULL;
return 0;
}
Sample input:
5
10 20 30 40 50
Exact output:
Average = 30.00
Example 2: Grow an array with realloc to append more values Program:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n, m;
if (scanf("%d", &n) != 1 || n < 0) { printf("Invalid input\n"); return 0; }
int *a = NULL;
if (n > 0) {
a = malloc((size_t)n * sizeof *a);
if (!a) { printf("Allocation failed\n"); return 0; }
for (int i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1) { printf("Invalid input\n"); free(a); return 0; }
}
}
if (scanf("%d", &m) != 1 || m < 0) { printf("Invalid input\n"); free(a); return 0; }
// Grow array to hold n + m items
size_t new_n = (size_t)n + (size_t)m;
int *tmp = realloc(a, new_n * sizeof *a);
if (!tmp && new_n > 0) { // on failure, a remains valid
printf("Reallocation failed\n");
free(a);
return 0;
}
a = tmp; // safe even if tmp is NULL when new_n == 0
for (int i = 0; i < m; i++) {
if (scanf("%d", &a[n + i]) != 1) {
printf("Invalid input\n");
free(a);
return 0;
}
}
long long sum = 0;
for (size_t i = 0; i < new_n; i++) sum += a[i];
printf("Count = %zu, Sum = %lld\n", new_n, sum);
free(a);
a = NULL;
return 0;
}
Sample input:
3
1 2 3
2
4 5
Exact output:
Count = 5, Sum = 15
Example 3: Dynamic 2D array using a single contiguous block Program:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int rows, cols;
if (scanf("%d %d", &rows, &cols) != 2 || rows <= 0 || cols <= 0) {
printf("Invalid input\n");
return 0;
}
size_t total = (size_t)rows * (size_t)cols;
int *mat = malloc(total * sizeof *mat);
if (!mat) {
printf("Allocation failed\n");
return 0;
}
// Fill with row*col pattern: value = (r+1)*(c+1)
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
mat[(size_t)r * (size_t)cols + (size_t)c] = (r + 1) * (c + 1);
}
}
// Print matrix
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
printf("%d%s", mat[(size_t)r * (size_t)cols + (size_t)c], (c == cols - 1) ? "\n" : " ");
}
}
free(mat);
mat = NULL;
return 0;
}
Sample input:
3 4
Exact output:
1 2 3 4
2 4 6 8
3 6 9 12
Common mistakes
- Casting the return of malloc/calloc/realloc in C, which can hide missing header problems. Do not cast in C.
- Not checking for NULL after allocation or reallocation before using the memory.
- Using memory after free (dangling pointer) or freeing the same pointer twice (double free). Set pointer to NULL after free and ensure a single ownership path.
- Writing beyond allocated bounds due to wrong size calculation (e.g., malloc(n) instead of malloc(n * sizeof *p)). Always use sizeof with the pointed type.
- Overflow in size calculations when multiplying count by size. Validate inputs and check before multiplication; prefer calloc(count, size) where suitable.
- Assuming calloc zeroing initializes pointers to NULL or floating-point to +0.0. In C, calloc only guarantees that all bytes are set to zero; integers become 0 because 0 has an all-bits-zero representation, but neither a null pointer nor +0.0 are required to be all-bits-zero on all platforms (even though they usually are). Do not rely on bit patterns; explicitly initialize if you need a particular value.
- Mixing allocation and deallocation APIs (e.g., using free on memory not allocated by malloc-family, or on stack/global memory). Only free what you allocated with malloc/calloc/realloc. Also, do not pass an interior pointer (an offset into a block) to free; you must pass the original pointer value returned by the allocator.
- Storing the result of realloc directly into the original pointer without a temporary. On failure, you lose the original pointer and leak memory. Use a temporary pointer.
- Forgetting to release all allocated blocks on every control path (including early returns on error). Use consistent cleanup.
- Using uninitialized pointers (wild pointers). Initialize to NULL.
- Confusing stack arrays with heap arrays: int a[100] is automatic storage, not dynamic; it disappears when the function returns.
For your exam
- Short notes: Advantages of dynamic allocation (flexibility, memory efficiency), disadvantages (complexity, leaks, fragmentation), difference between malloc and calloc, realloc usage and safety pattern, alignment and sizeof.
- Programs: Read N and process array using malloc; grow array with realloc; dynamic 2D array allocation and traversal. For full marks, include headers, error checks for NULL, correct size calculations with sizeof, correct freeing, and exact output formatting.
- Diagram questions: Draw and label memory layout (code, data/BSS, heap growth, stack growth). For full marks, clearly label each region, show a pointer on the stack to a heap block, and note that exact directions are conceptual.
- Conceptual questions: Explain memory leak and dangling pointer with examples; describe what happens on realloc success/failure; explain why not to cast malloc’s return in C; discuss fragmentation.
- Pitfalls: Demonstrate safe patterns: temporary for realloc, free-and-NULL, bounds checks, using size_t, and overflow-aware size calculation.
Quick check
- Which function zero-initializes the allocated memory: malloc or calloc, and what does it return on failure?
- Why is it safer to write
int *p = malloc(n * sizeof *p);thanint *p = malloc(n * sizeof(int));? - After
free(p);, ispautomatically set to NULL? What is the safe practice immediately after freeing?
Answers: 1) calloc, and it returns NULL on failure. 2) sizeof *p tracks the pointer’s target type automatically if the type of p changes, reducing errors; both are correct if consistent. 3) No; p retains its old (dangling) value. Safe practice: set p = NULL right after free.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?