In C, what function is used to dynamically allocate memory?

The story behind the answer

The C function used to dynamically allocate memory is `malloc`.

Declared in `<stdlib.h>`, `malloc` requests a block of memory at run time and returns a pointer to its first byte. The requested size is given in bytes, commonly calculated with `sizeof`, as in `malloc(10 * sizeof(int))`. The returned pointer is typically assigned to a typed pointer in C without an explicit cast.

Memory obtained with `malloc` is uninitialized: its bytes contain indeterminate values until the program stores data in them. If the allocation cannot be satisfied, `malloc` returns a null pointer, so robust code checks the result before using it.

The related functions have distinct jobs. `calloc` allocates space for multiple elements and initializes the bytes to zero; `realloc` changes the size of an existing allocation; and `free` releases memory previously obtained from an allocation function. Forgetting `free` can create a memory leak, while using a pointer after freeing it creates a dangling-pointer bug.

Source: Wikipedia · fact-checked Aug. 2026

Add question to a list

Choose a list to keep this question in: