C malloc and free
last modified November 14, 2026
An ordinary array in C has a size fixed when the program is compiled, and a
local array disappears when the function that declares it returns. Variable
length arrays relax the first limit but not the second, and a large one can
overflow the stack. Dynamic allocation removes both limits: malloc
obtains a block of memory of any size while the program runs, and the block stays
alive until free returns it. This tutorial covers allocation and
release of arrays, strings and structures, resizing with realloc,
zero-initialization with calloc, two-dimensional arrays, size
overflow, error handling, aligned allocation, dangling pointers, memory leaks and
finding memory bugs with AddressSanitizer.
What malloc and free do
malloc takes a size in bytes and returns a pointer to the start of a
newly allocated block, or NULL when the request cannot be satisfied.
The memory it returns is uninitialized. free takes a pointer
returned by an allocation function and returns the block to the allocator; after
that the pointer must not be used again.
void *malloc(size_t size); void free(void *ptr);
The return type void * converts to any object pointer type in C, so
the result of malloc is assigned to a typed pointer without a cast.
The argument is a number of bytes, and the portable way to express it is
count * sizeof *ptr, where sizeof *ptr is the size of
one element and therefore follows the type of ptr if it changes.
Allocating an array of integers
The first example allocates room for five integers, fills it, prints the values and releases the block. The result of the allocation is checked before the pointer is used.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *vals = malloc(5 * sizeof *vals);
if (vals == NULL) {
fprintf(stderr, "memory allocation failed\n");
return 1;
}
for (int i = 0; i < 5; i++) {
vals[i] = i + 1;
}
for (int i = 0; i < 5; i++) {
printf("%d ", vals[i]);
}
printf("\n");
free(vals);
return 0;
}
A pointer returned by malloc is used exactly like an array: the
subscript operator works because the block is contiguous. The block is not an
array object, however, so sizeof vals gives the size of the pointer
and not the size of the allocation; the count must be kept in a separate
variable. Failing to check for NULL would turn a failed allocation
into a crash on the first write.
$ gcc -std=c17 -Wall -Wextra -o basic_allocation basic_allocation.c $ ./basic_allocation 1 2 3 4 5
Allocating a string
A string needs one byte for every character plus one for the terminating null character. The next program asks for exactly that many bytes, copies the text into the block and prints it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
const char *text = "Hello there!";
char *str = malloc(strlen(text) + 1);
if (str == NULL) {
fprintf(stderr, "memory allocation failed\n");
return 1;
}
strcpy(str, text);
printf("%s\n", str);
printf("length: %zu\n", strlen(str));
free(str);
return 0;
}
strlen counts the characters without the terminator, so the
+ 1 is what makes room for it. Omitting it is a classic off-by-one
error: strcpy would then write one byte past the end of the block.
Since sizeof(char) is 1 by definition, malloc may take
the character count directly.
$ gcc -std=c17 -Wall -Wextra -o string_allocation string_allocation.c $ ./string_allocation Hello there! length: 12
Duplicating a string with strdup
The allocate-and-copy pair from the previous example is so common that it has a
function of its own. strdup allocates strlen(s) + 1
bytes, copies the string including its terminator and returns the new block,
which the caller frees. It was a POSIX function for decades and became part of
standard C in C23. The next program makes modifiable copies of three string
literals.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
const char *words[] = { "falcon", "sky", "cloud" };
char *copies[3];
for (size_t i = 0; i < 3; i++) {
copies[i] = strdup(words[i]);
if (copies[i] == NULL) {
for (size_t j = 0; j < i; j++) {
free(copies[j]);
}
return 1;
}
}
copies[1][0] = 'S';
for (size_t i = 0; i < 3; i++) {
printf("%s %s\n", words[i], copies[i]);
free(copies[i]);
}
return 0;
}
String literals must not be modified, but the copies can be: the program
capitalizes the second one, and the originals stay unchanged. Each copy is a
separate allocation, so each is freed. If one strdup fails, the
copies made so far are released before the program exits. With glibc,
strdup is declared under -std=c2x or a POSIX feature
macro, but not under plain -std=c17, where the compiler reports an
implicit declaration. C23 also adds strndup, which copies at most a
given number of characters.
$ gcc -std=c2x -Wall -Wextra -o strdup_example strdup_example.c $ ./strdup_example falcon falcon sky Sky cloud cloud
Returning memory from a function
Local variables have automatic storage: they live on the stack and end when
their function returns. Memory from malloc has allocated storage:
it lives until it is freed, no matter which function created it. That is why a
function that builds a result of runtime size and hands it to its caller must
allocate it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *make_greeting(const char *name) {
size_t size = strlen("Hello, !") + strlen(name) + 1;
char *msg = malloc(size);
if (msg == NULL) {
return NULL;
}
snprintf(msg, size, "Hello, %s!", name);
return msg;
}
int main(void) {
char *msg = make_greeting("Lucia");
if (msg == NULL) {
fprintf(stderr, "memory allocation failed\n");
return 1;
}
printf("%s\n", msg);
free(msg);
return 0;
}
make_greeting computes the exact size of the message, allocates it,
formats the text into it with snprintf and returns the pointer.
Ownership passes to the caller, which is now responsible for the
free; a function like this should document that. The tempting
alternative returns a local array instead:
static char *make_greeting(const char *name) {
char msg[64];
snprintf(msg, sizeof msg, "Hello, %s!", name);
return msg;
}
Here msg ceases to exist when the function returns, so the caller
receives a dangling pointer and using it is undefined behavior. GCC detects this
case and warns function returns address of local variable
[-Wreturn-local-addr].
$ gcc -std=c17 -Wall -Wextra -o return_alloc return_alloc.c $ ./return_alloc Hello, Lucia!
Allocating a structure
A structure is allocated like any other object, with sizeof *p
giving its size. When the structure itself holds pointers to allocated memory,
the program has a small tree of allocations to build and to tear down. The usual
answer is a pair of functions, one that creates the object and one that destroys
it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person {
char *name;
int age;
};
static struct person *person_create(const char *name, int age) {
struct person *p = malloc(sizeof *p);
if (p == NULL) {
return NULL;
}
p->name = malloc(strlen(name) + 1);
if (p->name == NULL) {
free(p);
return NULL;
}
strcpy(p->name, name);
p->age = age;
return p;
}
static void person_destroy(struct person *p) {
if (p == NULL) {
return;
}
free(p->name);
free(p);
}
int main(void) {
struct person *p = person_create("Roger Roe", 34);
if (p == NULL) {
fprintf(stderr, "memory allocation failed\n");
return 1;
}
printf("%s is %d years old\n", p->name, p->age);
person_destroy(p);
return 0;
}
person_create allocates the structure, then the name it owns. If
the second allocation fails, the structure is freed before returning
NULL, so the caller gets either a complete object or nothing.
person_destroy releases in reverse order: the name first, because
after free(p) the member p->name could no longer be
read. Like free itself, the destroy function accepts
NULL, which simplifies cleanup code in callers.
$ gcc -std=c17 -Wall -Wextra -o struct_allocation struct_allocation.c $ ./struct_allocation Roger Roe is 34 years old
Flexible array members
A structure whose last member is an array without a size,
char data[];, has a flexible array member. The array contributes
nothing to sizeof of the structure, and its storage is provided by
allocating extra bytes after the structure. A header and a variable-length
payload then live in one block.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct buffer {
size_t len;
char data[];
};
static struct buffer *buffer_create(const char *text) {
size_t len = strlen(text);
struct buffer *b = malloc(sizeof *b + len + 1);
if (b == NULL) {
return NULL;
}
b->len = len;
memcpy(b->data, text, len + 1);
return b;
}
int main(void) {
struct buffer *b = buffer_create("an old falcon");
if (b == NULL) {
fprintf(stderr, "memory allocation failed\n");
return 1;
}
printf("sizeof(struct buffer): %zu\n", sizeof(struct buffer));
printf("%zu bytes: %s\n", b->len, b->data);
free(b);
return 0;
}
The allocation requests sizeof *b for the header plus
len + 1 bytes for the text and its terminator. The output shows that
the structure itself occupies only the 8 bytes of len. Compared with
a char * member, there is one allocation instead of two, one
free instead of two, and the data sits right next to its header.
The price is that the payload cannot be resized independently; growing it means
reallocating the whole block.
$ gcc -std=c17 -Wall -Wextra -o flexible_array flexible_array.c $ ./flexible_array sizeof(struct buffer): 8 13 bytes: an old falcon
Zero-initialized memory with calloc
calloc takes the number of elements and the size of one element,
multiplies them and clears the block to all bits zero. The next program allocates
five integers and prints them without assigning anything first.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *vals = calloc(5, sizeof *vals);
if (vals == NULL) {
return 1;
}
for (int i = 0; i < 5; i++) {
printf("%d ", vals[i]);
}
printf("\n");
free(vals);
return 0;
}
All five values are 0, whereas the same block from malloc would
contain whatever bytes happened to be there. Zeroing is not the same as
initializing to a useful value, but it gives a defined starting point. For
integers all-bits-zero is the value zero; for double and pointers
it is 0.0 and a null pointer on all common platforms, although the standard does
not promise it. calloc also checks the multiplication of its two
arguments for overflow, which is shown later.
$ gcc -std=c17 -Wall -Wextra -o calloc_example calloc_example.c $ ./calloc_example 0 0 0 0 0
Growing an array with realloc
realloc changes the size of an existing block. It either extends the
block in place or allocates a new one, copies the old contents and frees the old
block, and it returns the address of the resized block. The next program starts
with five integers and grows the array to ten.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t count = 5;
int *vals = malloc(count * sizeof *vals);
if (vals == NULL) {
fprintf(stderr, "memory allocation failed\n");
return 1;
}
for (size_t i = 0; i < count; i++) {
vals[i] = (int) i + 1;
}
int *tmp = realloc(vals, 10 * sizeof *vals);
if (tmp == NULL) {
fprintf(stderr, "memory reallocation failed\n");
free(vals);
return 1;
}
vals = tmp;
count = 10;
for (size_t i = 5; i < count; i++) {
vals[i] = (int) i + 1;
}
for (size_t i = 0; i < count; i++) {
printf("%d ", vals[i]);
}
printf("\n");
free(vals);
return 0;
}
The result is stored in tmp rather than assigned directly to
vals. If realloc fails it returns NULL and
leaves the original block untouched; assigning that NULL to
vals would lose the only pointer to the block and leak it. Only
after the success check is vals updated. The new elements, indices 5
through 9, are uninitialized and are written before they are read. Because the
block may have moved, any other pointers into the old block are invalid after a
successful realloc.
$ gcc -std=c17 -Wall -Wextra -o reallocation reallocation.c $ ./reallocation 1 2 3 4 5 6 7 8 9 10
A dynamic array with growing capacity
When the number of elements is not known in advance, for example when reading
input, the array grows as data arrives. Calling realloc for every
new element would copy the whole array each time. Instead the program keeps a
size, the number of elements in use, and a capacity, the number of elements
allocated, and doubles the capacity whenever the two meet.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(void) {
int *vals = NULL;
size_t size = 0;
size_t capacity = 0;
int n;
while (scanf("%d", &n) == 1) {
if (size == capacity) {
size_t new_capacity = capacity == 0 ? 4 : capacity * 2;
if (new_capacity > SIZE_MAX / sizeof *vals) {
fprintf(stderr, "array too large\n");
free(vals);
return 1;
}
int *tmp = realloc(vals, new_capacity * sizeof *vals);
if (tmp == NULL) {
fprintf(stderr, "memory reallocation failed\n");
free(vals);
return 1;
}
vals = tmp;
capacity = new_capacity;
printf("capacity grown to %zu\n", capacity);
}
vals[size++] = n;
}
long sum = 0;
for (size_t i = 0; i < size; i++) {
sum += vals[i];
}
printf("%zu values, sum %ld\n", size, sum);
free(vals);
return 0;
}
The array starts as a null pointer with zero capacity, and the first growth
calls realloc(NULL, ...), which behaves like malloc.
Doubling means the twenty values cause only four allocations, and the total
copying work stays proportional to the number of elements, so appending is
constant time on average. Before multiplying, the program checks that the new
byte count fits in size_t, which the next section explains. The
input comes from seq, which prints the numbers 1 to 20.
$ gcc -std=c17 -Wall -Wextra -o dynamic_array dynamic_array.c $ seq 1 20 | ./dynamic_array capacity grown to 4 capacity grown to 8 capacity grown to 16 capacity grown to 32 20 values, sum 210
Guarding against size overflow
The expression count * sizeof *ptr is computed in
size_t, an unsigned type, so a large count does not fail: it wraps
around modulo SIZE_MAX + 1 to a small number. malloc
then succeeds with a block far smaller than intended, and filling the array
writes past its end. The next program shows the wrap-around and two ways to
refuse such a request.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
static void *alloc_array(size_t count, size_t size) {
if (size != 0 && count > SIZE_MAX / size) {
return NULL;
}
return malloc(count * size);
}
int main(void) {
size_t count = SIZE_MAX / sizeof(int) + 2;
printf("elements requested: %zu\n", count);
printf("count * sizeof(int): %zu bytes\n", count * sizeof(int));
int *a = alloc_array(count, sizeof *a);
printf("alloc_array: %s\n", a == NULL ? "refused" : "allocated");
int *b = calloc(count, sizeof *b);
printf("calloc: %s\n", b == NULL ? "refused" : "allocated");
free(a);
free(b);
return 0;
}
The requested element count times four bytes wraps around to just 4 bytes, so a
plain malloc(count * sizeof(int)) would return a 4-byte block for
more than four quintillion elements. alloc_array checks the
multiplication before doing it: count > SIZE_MAX / size is true
exactly when the product would overflow. calloc performs the same
check internally and returns NULL. For resizing, glibc and POSIX
2024 provide reallocarray(ptr, count, size), a
realloc with the same check.
$ gcc -std=c17 -Wall -Wextra -o size_overflow size_overflow.c $ ./size_overflow elements requested: 4611686018427387905 count * sizeof(int): 4 bytes alloc_array: refused calloc: refused
A two-dimensional array
C has no built-in dynamic two-dimensional array, but one can be built as an array of pointers, where each pointer refers to a separately allocated row. The next program allocates three rows of four integers, fills them and prints a small matrix.
#include <stdio.h>
#include <stdlib.h>
enum { ROWS = 3, COLS = 4 };
int main(void) {
int **arr = malloc(ROWS * sizeof *arr);
if (arr == NULL) {
return 1;
}
for (int i = 0; i < ROWS; i++) {
arr[i] = malloc(COLS * sizeof *arr[i]);
if (arr[i] == NULL) {
for (int j = 0; j < i; j++) {
free(arr[j]);
}
free(arr);
return 1;
}
}
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
arr[i][j] = i * COLS + j + 1;
}
}
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%3d", arr[i][j]);
}
printf("\n");
}
for (int i = 0; i < ROWS; i++) {
free(arr[i]);
}
free(arr);
return 0;
}
There are two levels of allocation, so there must be two levels of release: the
rows are freed first, then the array of pointers. If the allocation of row
i fails, the loop frees the i rows that already exist
before releasing the pointer array, so no partially built structure leaks. The
%3d conversion keeps the columns aligned. This layout allows rows
of different lengths, a jagged array, but it costs one allocation per row and
scatters the rows across the heap.
$ gcc -std=c17 -Wall -Wextra -o 2d_array_allocation 2d_array_allocation.c $ ./2d_array_allocation 1 2 3 4 5 6 7 8 9 10 11 12
A contiguous two-dimensional array
When all rows have the same length, the whole matrix fits in one block. A
pointer to an array of cols integers, int (*m)[cols],
lets the program index that block with m[i][j]. Because
cols may be a runtime value, the dimensions here come from the
command line.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "usage: %s rows cols\n", argv[0]);
return 1;
}
size_t rows = strtoul(argv[1], NULL, 10);
size_t cols = strtoul(argv[2], NULL, 10);
if (rows == 0 || cols == 0) {
fprintf(stderr, "rows and cols must be positive\n");
return 1;
}
int (*m)[cols] = malloc(rows * sizeof *m);
if (m == NULL) {
fprintf(stderr, "memory allocation failed\n");
return 1;
}
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
m[i][j] = (int) (i * cols + j + 1);
}
}
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
printf("%3d", m[i][j]);
}
printf("\n");
}
printf("one block of %zu bytes\n", rows * sizeof *m);
free(m);
return 0;
}
sizeof *m is the size of one row, cols * sizeof(int),
computed at run time, so rows * sizeof *m is the size of the whole
matrix. There is one allocation, one free and no cleanup loop for
partial failures, and the rows are adjacent in memory, which is friendlier to
the processor cache. The type int (*)[cols] is a variably modified
type: C99 requires it, C11 and C17 make it optional, and C23 makes it mandatory
again, while leaving variable length arrays on the stack optional. GCC and Clang
support it in all modes.
$ gcc -std=c17 -Wall -Wextra -o contiguous_2d contiguous_2d.c $ ./contiguous_2d 3 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 one block of 60 bytes
Releasing several blocks with goto
A function that makes several allocations has several ways to fail, and each
early return must free what was allocated so far. Repeating the
free calls on every error path is error prone. The common C idiom
is a single cleanup label at the end of the function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int cmp_int(const void *a, const void *b) {
int x = *(const int *) a;
int y = *(const int *) b;
return (x > y) - (x < y);
}
static int print_stats(const int *data, size_t n) {
int ret = -1;
int *sorted = NULL;
char *line = NULL;
size_t line_size = 64;
sorted = malloc(n * sizeof *sorted);
if (sorted == NULL) {
goto cleanup;
}
memcpy(sorted, data, n * sizeof *sorted);
qsort(sorted, n, sizeof *sorted, cmp_int);
line = malloc(line_size);
if (line == NULL) {
goto cleanup;
}
snprintf(line, line_size, "min %d, median %d, max %d",
sorted[0], sorted[n / 2], sorted[n - 1]);
puts(line);
ret = 0;
cleanup:
free(line);
free(sorted);
return ret;
}
int main(void) {
int data[] = { 7, -2, 13, 5, 0, 9, 4 };
if (print_stats(data, sizeof data / sizeof data[0]) != 0) {
fprintf(stderr, "memory allocation failed\n");
return 1;
}
return 0;
}
Both pointers start as NULL, and every failure jumps to
cleanup. Since free(NULL) does nothing, the cleanup
code frees both pointers unconditionally, whether they were allocated or not,
and success and failure leave the function through the same path. The return
value ret is set to success only after all the work is done. The
function sorts a copy with qsort so the caller's data stays
unchanged.
$ gcc -std=c17 -Wall -Wextra -o cleanup_goto cleanup_goto.c $ ./cleanup_goto min -2, median 5, max 13
Zero sizes and null pointers
A few corner cases of the allocation functions are worth knowing, because the standard leaves some of them to the implementation. The next program exercises them with glibc.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
void *p = malloc(0);
printf("malloc(0) returned %s\n", p == NULL ? "NULL" : "a non-null pointer");
free(p);
int *q = realloc(NULL, 4 * sizeof *q);
printf("realloc(NULL, n) allocated: %s\n", q == NULL ? "no" : "yes");
free(q);
q = NULL;
free(q);
printf("free(NULL) did nothing\n");
return 0;
}
malloc(0) returns either NULL or a unique pointer that
must not be dereferenced but must be freed; glibc returns a pointer. Portable
code therefore does not treat NULL from a zero-size request as an
error. realloc(NULL, n) is equivalent to malloc(n),
which the dynamic array above relies on, and free(NULL) is always
a no-op. The opposite case, realloc(ptr, 0), is
implementation-defined in C17 and undefined behavior in C23; to release a block,
call free.
$ gcc -std=c17 -Wall -Wextra -o edge_cases edge_cases.c $ ./edge_cases malloc(0) returned a non-null pointer realloc(NULL, n) allocated: yes free(NULL) did nothing
Aligned allocation
malloc returns memory suitably aligned for any standard type, which
means alignment to alignof(max_align_t). Some uses need more, for
example SIMD instructions or data that should start on a cache line. C11
aligned_alloc takes the alignment as its first argument.
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
#include <stdalign.h>
int main(void) {
printf("malloc alignment: %zu\n", alignof(max_align_t));
double *p = aligned_alloc(64, 8 * sizeof *p);
if (p == NULL) {
fprintf(stderr, "memory allocation failed\n");
return 1;
}
printf("64-byte aligned: %s\n", (uintptr_t) p % 64 == 0 ? "yes" : "no");
free(p);
return 0;
}
On x86-64 Linux malloc guarantees 16-byte alignment. The request for
eight doubles, 64 bytes, aligned to 64 succeeds, and the address is a multiple
of 64. The alignment must be a power of two supported by the implementation, and
since C17 the size need not be a multiple of the alignment, though older
implementations required it. The block is released with the ordinary
free. C23 adds two more release functions,
free_sized and free_aligned_sized, which pass the size
back to the allocator as an optimization hint; glibc 2.35 does not provide them
yet.
$ gcc -std=c17 -Wall -Wextra -o aligned aligned.c $ ./aligned malloc alignment: 16 64-byte aligned: yes
Freeing memory and dangling pointers
After free, the block no longer belongs to the program, but the
pointer variable still holds its old address. Such a pointer is called dangling,
and reading or writing through it is undefined behavior; even reading the
pointer's value is not allowed. A common defense is to set the pointer to
NULL right after freeing it, and a small helper does both.
#include <stdio.h>
#include <stdlib.h>
static void free_and_clear(int **pp) {
free(*pp);
*pp = NULL;
}
int main(void) {
int *vals = malloc(3 * sizeof *vals);
if (vals == NULL) {
fprintf(stderr, "memory allocation failed\n");
return 1;
}
vals[0] = 1;
vals[1] = 2;
vals[2] = 3;
printf("before free: %d %d %d\n", vals[0], vals[1], vals[2]);
free_and_clear(&vals);
free_and_clear(&vals);
if (vals == NULL) {
printf("vals is NULL, the second release did nothing\n");
}
return 0;
}
free_and_clear takes the address of the pointer, so it can clear
the caller's variable. The second call is harmless because freeing a null
pointer does nothing, and an accidental dereference of vals would
now usually crash at once instead of silently reading freed memory, although it
is still undefined behavior. The protection covers only that one variable. Any
other copy of the address dangles as before:
int *alias = vals; free_and_clear(&vals); alias[0] = 4;
After the call vals is NULL, but alias
still holds the old address, and the write goes into freed memory. Clearing a
pointer does not replace knowing which part of the program owns a block.
$ gcc -std=c17 -Wall -Wextra -o dangling dangling.c $ ./dangling before free: 1 2 3 vals is NULL, the second release did nothing
Memory leaks
A leak happens when the last pointer to an allocated block is lost before the block is freed. The program keeps running and may produce perfectly correct results, while its memory use grows with every lost block. The next program allocates an array in a helper function and never frees it.
#include <stdio.h>
#include <stdlib.h>
static int *make_values(size_t count) {
int *vals = malloc(count * sizeof *vals);
if (vals == NULL) {
return NULL;
}
for (size_t i = 0; i < count; i++) {
vals[i] = (int) (i * i);
}
return vals;
}
int main(void) {
int *vals = make_values(5);
if (vals == NULL) {
return 1;
}
printf("%d %d %d\n", vals[0], vals[1], vals[4]);
/* free(vals) is missing: the block stays allocated */
return 0;
}
The output is correct and nothing signals the mistake; the operating system
reclaims the block when the process ends, which is why a leak in a short program
is invisible. In a long-running program the same pattern exhausts memory. The
rule is that every successful allocation must have exactly one matching
free, on every path out of the function, including error paths. The
next section shows how to make such a leak visible.
$ gcc -std=c17 -Wall -Wextra -o leak leak.c $ ./leak 0 1 16
Detecting memory errors with AddressSanitizer
Leaks, use after free and double frees often go unnoticed in testing, because
the program happens to work. AddressSanitizer, built into GCC and Clang, adds
checks to every memory access and to the allocation functions, and reports the
first error with the source lines involved. It is enabled with
-fsanitize=address, and -g adds the file names and
line numbers. The instrumented program runs about twice as slow, so it is a
testing and debugging build, not a release build. Valgrind's Memcheck finds the
same kinds of errors in an uninstrumented binary, at a larger slowdown.
Finding a leak
The leak.c program from the previous section needs no change. Built
with the sanitizer, it prints its normal output, and at exit the leak checker
lists every block that is still allocated and no longer reachable.
$ gcc -std=c17 -Wall -g -fsanitize=address -o leak leak.c
$ ./leak
0 1 16
=================================================================
==88704==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 20 byte(s) in 1 object(s) allocated from:
#0 0x7b8d6eb2c30f in malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:67
#1 0x0000004011b1 in make_values /home/jano/fm-demo/leak.c:6
#2 0x000000401253 in main /home/jano/fm-demo/leak.c:21
#3 0x7b8d6e629d8f in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
SUMMARY: AddressSanitizer: 20 byte(s) leaked in 1 allocation(s).
Use after free
The next program reproduces the alias problem from the dangling pointer section: it frees a block through one pointer and reads it through another.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *vals = malloc(3 * sizeof *vals);
if (vals == NULL) {
return 1;
}
vals[0] = 10;
int *alias = vals;
free(vals);
vals = NULL;
printf("%d\n", alias[0]);
return 0;
}
Without the sanitizer this program would most likely print 10 or some other
leftover value and exit normally. GCC's -Wuse-after-free warning,
part of -Wall, already spots this simple case at compile time; the
sanitizer also catches the cases the compiler cannot see, such as a free in one
function and a use in another. The report names the kind of error, the line of
the bad read and the line of the free. The output is cut to its
first twelve lines; the full report continues with the allocation site and a map
of the memory around the address.
$ gcc -std=c17 -Wall -g -fsanitize=address -o use_after_free use_after_free.c
use_after_free.c: In function ‘main’:
use_after_free.c:19:5: warning: pointer ‘alias’ used after ‘free’ [-Wuse-after-free]
19 | printf("%d\n", alias[0]);
| ^~~~~~~~~~~~~~~~~~~~~~~~
use_after_free.c:16:5: note: call to ‘free’ here
16 | free(vals);
| ^~~~~~~~~~
$ ./use_after_free 2>&1 | head -n 12
=================================================================
==88131==ERROR: AddressSanitizer: heap-use-after-free on address 0x7b1ae3fe0010 at pc 0x000000401261 bp 0x7ffcd880e3a0 sp 0x7ffcd880e390
READ of size 4 at 0x7b1ae3fe0010 thread T0
#0 0x000000401260 in main /home/jano/fm-demo/use_after_free.c:19
#1 0x7efae4e29d8f in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
#2 0x7efae4e29e3f in __libc_start_main_impl ../csu/libc-start.c:392
#3 0x0000004010e4 in _start (/home/jano/fm-demo/use_after_free+0x4010e4)
0x7b1ae3fe0010 is located 0 bytes inside of 12-byte region [0x7b1ae3fe0010,0x7b1ae3fe001c)
freed by thread T0 here:
#0 0x7efae532b10f in free ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:51
#1 0x000000401221 in main /home/jano/fm-demo/use_after_free.c:16
Double free
Freeing the same block twice corrupts the allocator's bookkeeping, and the damage can surface much later in an unrelated allocation. The next program frees one block through two pointers.
#include <stdlib.h>
int main(void) {
char *buf = malloc(16);
if (buf == NULL) {
return 1;
}
char *copy = buf;
free(buf);
free(copy);
return 0;
}
The two pointers hold the same address, so the second free releases
a block that is already gone. AddressSanitizer stops the program at that call
and shows both free calls, lines 14 and 13.
$ gcc -std=c17 -Wall -g -fsanitize=address -o double_free double_free.c
double_free.c: In function ‘main’:
double_free.c:14:5: warning: pointer ‘copy’ used after ‘free’ [-Wuse-after-free]
14 | free(copy);
| ^~~~~~~~~~
double_free.c:13:5: note: call to ‘free’ here
13 | free(buf);
| ^~~~~~~~~
$ ./double_free 2>&1 | head -n 12
=================================================================
==88138==ERROR: AddressSanitizer: attempting double-free on 0x6ce0fa9e0010 in thread T0:
#0 0x70c0fbd2b10f in free ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:51
#1 0x000000401199 in main /home/jano/fm-demo/double_free.c:14
#2 0x70c0fb829d8f in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
#3 0x70c0fb829e3f in __libc_start_main_impl ../csu/libc-start.c:392
#4 0x000000401094 in _start (/home/jano/fm-demo/double_free+0x401094)
0x6ce0fa9e0010 is located 0 bytes inside of 16-byte region [0x6ce0fa9e0010,0x6ce0fa9e0020)
freed by thread T0 here:
#0 0x70c0fbd2b10f in free ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:51
#1 0x00000040118d in main /home/jano/fm-demo/double_free.c:13
Rules for using malloc and free
The rules below prevent nearly all dynamic-memory bugs. They follow from the fact that the allocator tracks blocks, not pointers, so the program must keep exactly one release per block and must never touch a block after releasing it.
- Check the result of
malloc,callocandreallocbefore using it. - Check
count * sizefor overflow, or letcallocdo it. - Store the result of
reallocin a temporary pointer, and free the original block if it fails. - Free every block exactly once, with
free, whichever function allocated it, and set the pointer toNULLafterwards. - Free the members a structure owns, and the rows of a two-dimensional array, before freeing the structure or the array of pointers.
- Free only the pointer an allocation function returned, never a pointer into the middle of the block or to memory that was not allocated.
- Never use a pointer after
free, and remember that copies of the pointer dangle too. - Never return the address of a local variable; allocate the result and document that the caller frees it.
- Prefer
sizeof *ptroversizeof(type)so the size follows the pointer's type. - Test with
-fsanitize=addressor Valgrind.
Source
cppreference: malloc
cppreference: free
cppreference: realloc
cppreference: calloc
cppreference: aligned_alloc
cppreference: strdup
GCC: Program Instrumentation Options
This tutorial covered dynamic memory in C: allocating arrays, strings and
structures, returning allocated memory from functions, flexible array members,
clearing memory with calloc, resizing with realloc and
growing a dynamic array, guarding against size overflow, two-dimensional arrays
in two layouts, cleanup with goto, zero-size requests, aligned
allocation, dangling pointers, leaks, and finding memory errors with
AddressSanitizer. The string functions that fill such blocks are covered in
C strcpy and C memcpy,
and the automatic storage that disappears when a function returns is described
in C variable.
Author
List all C tutorials.