malloc in C reserves a block of memory on the heap and returns a pointer to it, or NULL if it could not. You give the block back with free when you are done, and you must check for NULL before using the pointer.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
size_t count = 5;
int *numbers = malloc(count * sizeof *numbers);
if (numbers == NULL) {
fprintf(stderr, "out of memory\n");
return 1;
}
for (size_t i = 0; i < count; i++)
numbers[i] = (int)(i * i);
printf("%d\n", numbers[4]);
free(numbers);
numbers = NULL;
return 0;
}
Example output:
16
How malloc works in C
The prototype, from <stdlib.h>, is void *malloc(size_t size). You pass a size in bytes and get back a void *. In C a void * converts to any object pointer type without a cast, so int *numbers = malloc(...) is correct as written. (C++ requires the cast, but C++ code normally uses new or containers instead.)
The block comes from the heap, not the stack. A local array disappears when its function returns. A malloc block stays valid until you free it, so it can outlive the function that created it and can be sized at run time. Those two properties are the reasons to use it: you need the data to survive, or you do not know the size until the program runs.
The Linux man page states that with malloc "the memory is not initialized". Reading a byte you have not written gives an unspecified value, and your program may appear to work on one run and fail on the next. The cppreference page adds that the returned pointer is suitably aligned for any object type with fundamental alignment, so you never need to align it by hand for ordinary types such as int, double or a struct.
How to calculate the size
Write the size as count * sizeof *pointer, as in the example. sizeof *numbers is the size of whatever numbers points to, so if you later change int to long the allocation changes with it. The alternative, malloc(5 * sizeof(int)), silently allocates the wrong amount if you change only the declaration.
A multiplication can overflow. If count comes from user input or a file, count * sizeof *numbers may wrap around to a small number, malloc succeeds, and your loop then writes far past the end of the block. The man page warns that an integer overflow "would not be detected" in a multiplied malloc call. Either check that count <= SIZE_MAX / sizeof *numbers before calling malloc, or use calloc, which does the check for you.
Always check for NULL
On failure the allocation functions "return NULL and set errno", per the man page. On Linux the error is ENOMEM, which the page describes as out of memory, possibly because the application hit the RLIMIT_AS or RLIMIT_DATA limit. Small allocations rarely fail on a desktop machine, which is exactly why unchecked code survives testing and then crashes on an embedded device, in a container with a memory limit, or when a huge size arrives from untrusted input.
Writing through a NULL pointer is undefined behavior. A guard clause at the top is the simplest handling: return an error code to the caller, or print a message and exit if the program cannot continue without the memory.
malloc, calloc and realloc compared
| Function | Arguments | Initial contents | Use it for |
|---|---|---|---|
malloc | total bytes | Uninitialized | A block you will fill completely yourself |
calloc | element count, element size | All bytes zero | Arrays, and anything that must start zeroed |
realloc | old pointer, new total bytes | Old data kept; added bytes uninitialized | Growing or shrinking an existing block |
free | pointer | Not applicable | Releasing a block |
calloc(count, size) sets the memory to zero, and the man page says that if multiplying the two arguments would overflow, calloc returns an error. Zeroed bytes are an all-bits-zero pattern. That is a valid value for integers on every common platform, but the C standard does not promise that all-bits-zero is a null pointer or a 0.0 floating-point value on every system, so do not rely on it for those types in portable code.
How to grow a block with realloc
realloc(pointer, new_size) changes the size of a block and keeps the existing contents up to the smaller of the old and new sizes. The block may move, so the old pointer can become invalid. That leads to the most common realloc mistake:
/* Wrong: if realloc fails, numbers is overwritten with NULL
and the original block can no longer be freed. */
numbers = realloc(numbers, new_count * sizeof *numbers);
On failure realloc returns NULL but leaves the original block allocated. Assign the result to a temporary first:
int *grown = realloc(numbers, new_count * sizeof *numbers);
if (grown == NULL) {
free(numbers); /* or keep using the old block */
return 1;
}
numbers = grown;
Two special cases from the man page are worth knowing. realloc(NULL, size) is equivalent to malloc(size), which lets a growing-array loop start from a NULL pointer. And realloc(pointer, 0) with a non-NULL pointer is documented on Linux as equivalent to free(pointer). The C standard treats a zero size as implementation-defined territory, so avoid passing zero and call free explicitly. The bytes added when a block grows are not initialized.
When you append items one at a time, do not grow by one element each time. Doubling the capacity when it fills keeps the number of reallocations small.
How to free memory correctly
free(pointer) releases the block. The man page says the pointer "must have been returned by a previous call to malloc() or related functions", and that "if p is NULL, no operation is performed". The rules that follow:
- Free each block exactly once. Freeing the same pointer twice (a double free) is undefined behavior.
- Do not free pointers that did not come from malloc. That includes the address of a local variable, a string literal, or a pointer into the middle of a block (such as
numbers + 2). - Do not use a block after freeing it. The pointer value still exists, but reading or writing through it is undefined behavior (use after free).
- Set the pointer to NULL after freeing it when it stays in scope. A second
freethen does nothing, and a stray dereference crashes at once instead of corrupting data quietly. This does not help if another copy of the pointer exists elsewhere.
For structures that contain pointers, free the inner blocks before the outer one. If you free the struct first, you lose the addresses of the inner blocks and they leak:
struct person {
char *name; /* heap-allocated */
int age;
};
void person_destroy(struct person *p)
{
if (p == NULL)
return;
free(p->name);
free(p);
}
Putting the cleanup in one function like this, and calling it from every exit path, is the main defence against leaks in larger programs. The same idea applies to goto cleanup; blocks in functions with several allocations: each failure jumps to a single section that frees everything allocated so far.
What a memory leak is in C
A memory leak is a block that has been allocated and never freed, with no pointer left to it. The usual causes are small and ordinary:
- A function allocates a buffer and returns early on an error path without freeing it.
- A pointer is reassigned before the block it held is freed, for example
buffer = malloc(100);twice in a row. - The realloc pattern above, where the only pointer is overwritten with NULL.
- A function documents that the caller must free its result, and the caller does not.
- A loop allocates one block per iteration and frees none of them.
A leak in a short command-line tool is harmless in practice, because the operating system reclaims the process's memory at exit. In a server, a daemon or a game loop it is a slow failure: memory use climbs until the process is killed or allocations start returning NULL.
How to find leaks and bad frees with AddressSanitizer
You do not have to find these by reading code. AddressSanitizer is built into GCC and Clang. The Clang documentation compiles its example with:
clang -O1 -g -fsanitize=address -fno-omit-frame-pointer program.c -o program
./program
GCC accepts the same -fsanitize=address flag. The Clang page lists use-after-free and out-of-bounds accesses to heap, stack and globals among the bugs it catches, and reports them as errors such as heap-use-after-free with a stack trace of the access, the allocation and the free. It also includes leak detection (marked experimental on that page). Per the page, leak detection is turned on by default on Linux and can be enabled on macOS with ASAN_OPTIONS=detect_leaks=1. When a program with a leak exits, you get a summary naming the allocation site, which points straight at the missing free.
Sanitizers slow the program and use extra memory, so use them in development and test builds, not in the release you ship. A debugger helps with the symptoms (a crash on a NULL or freed pointer), and reading that crash output is the same skill as in the recursion article's stack overflow section, where a deep call chain is the thing to spot.
Common malloc mistakes
- Allocating the wrong size for a string. A C string of 5 characters needs 6 bytes, because of the terminating
'\0'. Usestrlen(text) + 1. - Using
sizeofon a pointer. Inside a function that receivesint *numbers,sizeof numbersis the size of the pointer (commonly 8 bytes on 64-bit systems), not the size of the block. Pass the element count separately. - Reading uninitialized memory. Fill the block before you read it, or use calloc.
- Writing one element past the end. A block of
countelements has valid indexes 0 tocount - 1. - Returning a pointer to a local array. That memory is gone when the function returns. Allocate with malloc, or let the caller pass in a buffer.
When malloc(0) is a problem
The result of malloc(0) varies. The Linux man page says it returns a unique pointer value that can be passed to free. cppreference says the behavior is implementation-defined: it may return NULL, or a non-NULL pointer that you must not dereference and should pass to free. That means a NULL return from malloc(0) is not necessarily an out-of-memory error. If your code can compute a size of zero, handle that case before calling malloc rather than treating NULL as failure.
Frequently asked questions
- What does malloc return in C?
- malloc returns a pointer to the start of a block of the requested number of bytes, or NULL if the allocation failed. The memory is not initialized, so it contains unspecified values until you write to it. The pointer is suitably aligned for any object type with fundamental alignment.
- Do I have to free memory from malloc?
- Yes. C has no garbage collector, so every block you get from malloc, calloc or realloc must be released with free once you no longer need it. When the program exits, the operating system reclaims its memory, but a long-running program that skips free will keep growing.
- What is the difference between malloc and calloc?
- calloc takes an element count and an element size, sets the memory to zero, and reports an error if multiplying the two would overflow. malloc takes a single byte count, leaves the memory uninitialized, and does not detect an overflow in a multiplication you wrote yourself.
- What happens if I call free twice on the same pointer?
- That is undefined behavior. The man page says free must be given a pointer returned by malloc or a related function, and a block that was already freed no longer qualifies. Setting the pointer to NULL after free is a common habit, because free(NULL) does nothing.