malloc(3)

C library function

Reserves a block of memory on the heap and returns its address, or NULL if the allocation fails. The contents are uninitialized; the block is yours until free.

Synopsis
#include <stdlib.h>
void *malloc(size_t size);

Description

malloc asks the system for size contiguous bytes on the heap and returns the address of the first one. The block lives until you hand it back with free(3), whichever function created it: that is what sets the heap apart from the stack, where a variable disappears at the end of its block. The C23 standard (ISO/IEC 9899, 2024 edition) says it plainly: the representation of the block is indeterminate. In other words, the bytes you get contain anything, often leftovers from an earlier allocation. If you need memory set to zero, use calloc(3).

The return type is void *, which converts to any object pointer type without an explicit cast in C. Write int *t = malloc(n * sizeof(int));, with no cast.

Return value

The address of the block on success, NULL on failure. Always test this return value before you dereference the pointer: writing through a NULL pointer triggers a segmentation fault. Failure happens when memory runs out, but also, on Linux, long after malloc returned an address: the kernel overcommits memory by default, so a huge block can look allocated and then get the process killed at the moment you actually write to it.

malloc(0) is an edge case: the standard allows either NULL or a unique pointer that you can pass to free but must not dereference. Build nothing on it.

Example

scores.c
#include <stdio.h>#include <stdlib.h>
int main(void){    int *scores = malloc(3 * sizeof(int));
    if (scores == NULL)        return 1;    for (int i = 0; i < 3; i++)        scores[i] = (i + 1) * 10;    printf("%d %d %d\n", scores[0], scores[1], scores[2]);    free(scores);    return 0;}
Terminal
$ gcc -Wall -Wextra -g scores.c -o scores$ ./scores10 20 30

Pitfalls

  • Not testing for NULL: the first access crashes instead of reporting the lack of memory cleanly.

  • Computing the size as n * sizeof(type) without watching for overflow. When n comes from outside, the product can overflow size_t and you allocate too little. calloc does that check for you.

  • Forgetting the matching free: every malloc gets exactly one free, or the memory leaks. A Valgrind report shows it.

  • Losing the only pointer to the block (reassigning it, leaving the function without returning it): the block still exists, but nobody can free it anymore.

Now write it yourself.