Lesson 2 of 5
malloc & calloc - Heap Allocation Patterns
`malloc(n)` allocates `n` bytes of uninitialised heap memory and returns a `void*`. `calloc(count, size)` allocates `count * size` bytes and **zero-initialises** them. Both return `NULL` on failure - this is a real possibility on embedded systems and under memory pressure. **Always check the return value.** Forgetting this check is a production bug.
malloc & calloc - Allocation, Null Check & Usage Patterns
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ── Correct malloc pattern ──────────────────────────────── */
int *create_array(int n) {
/* sizeof(int) * n - always use sizeof to be portable */
int *arr = malloc((size_t)n * sizeof(int));
if (arr == NULL) { /* ALWAYS check - malloc can fail! */
fprintf(stderr, "malloc failed for %d ints
", n);
return NULL; /* caller must handle NULL return */
}
/* arr contains GARBAGE - uninitialised! */
return arr;
}
/* ── calloc - allocation + zero initialisation ─────────── */
int *create_zeroed_array(int n) {
/* calloc(count, size) = malloc(count*size) + memset 0 */
int *arr = calloc((size_t)n, sizeof(int));
if (arr == NULL) {
fprintf(stderr, "calloc failed
");
return NULL;
}
/* arr is guaranteed to be all zeros */
return arr;
}
/* ── Duplicate a string on the heap ─────────────────────── */
char *str_dup(const char *src) {
size_t len = strlen(src) + 1; /* +1 for null terminator */
char *dst = malloc(len);
if (dst == NULL) return NULL;
memcpy(dst, src, len); /* faster than strcpy for known length */
return dst;
}
int main(void) {
int n = 10;
/* ── malloc - uninitialised ─────────────────────────── */
int *a = create_array(n);
if (a == NULL) return 1;
for (int i = 0; i < n; i++) a[i] = i * i; /* must initialise before use */
printf("Squares: ");
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("
");
free(a); /* MUST free every malloc'd allocation */
a = NULL; /* defensively null after free */
/* ── calloc - pre-zeroed ─────────────────────────────── */
int *b = create_zeroed_array(n);
if (b == NULL) return 1;
printf("All zeros: %d %d %d
", b[0], b[1], b[9]); /* 0 0 0 */
free(b);
b = NULL;
/* ── Heap string duplicate ───────────────────────────── */
char *s = str_dup("hello, heap!");
if (s == NULL) return 1;
printf("Heap string: %s
", s);
s[0] = 'H'; /* OK: writable heap memory */
printf("Modified: %s
", s);
free(s);
s = NULL;
return 0;
}Common Mistakes
- Not checking `malloc` return value - on embedded systems with limited RAM, `malloc` fails regularly. Always: `if (ptr == NULL) { handle_error(); return; }`.
- Computing allocation size incorrectly - `malloc(n)` when you need `n` ints should be `malloc(n * sizeof(int))`. Forgetting `sizeof` allocates too few bytes for non-char types.
- Using `sizeof(ptr)` instead of `sizeof(*ptr)` - `malloc(sizeof(p))` on a 64-bit system allocates 8 bytes (pointer size), not `sizeof(T)`. Use `malloc(sizeof(*p))` which gives the size of what p points to - correct regardless of type.
Tip
Tip
Practice malloc calloc Heap Allocation Patterns in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
malloc allocates raw bytes; calloc allocates and zeroes memory; both return NULL on failure
Practice Task
Note
Practice Task - (1) Write a working example of malloc calloc Heap Allocation Patterns from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with malloc calloc Heap Allocation Patterns is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.
Key Takeaways
- `malloc(n)` allocates `n` bytes of uninitialised heap memory and returns a `void*`.
- Not checking `malloc` return value - on embedded systems with limited RAM, `malloc` fails regularly. Always: `if (ptr == NULL) { handle_error(); return; }`.
- Computing allocation size incorrectly - `malloc(n)` when you need `n` ints should be `malloc(n * sizeof(int))`. Forgetting `sizeof` allocates too few bytes for non-char types.
- Using `sizeof(ptr)` instead of `sizeof(*ptr)` - `malloc(sizeof(p))` on a 64-bit system allocates 8 bytes (pointer size), not `sizeof(T)`. Use `malloc(sizeof(*p))` which gives the size of what p points to - correct regardless of type.
Finished this lesson?