When you need memory that outlives a function or whose size is decided at run time, you ask for it with malloc.
Direct answer
malloc(size) allocates size bytes on the heap and returns a pointer, or NULL if it fails. Check the result, use the memory, then release it with free. Set the pointer to NULL afterwards to avoid using freed memory.
Example
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 5;
int *numbers = malloc(n * sizeof *numbers);
if (numbers == NULL) {
return 1;
}
for (int i = 0; i < n; i++) numbers[i] = i * i;
for (int i = 0; i < n; i++) printf("%d ", numbers[i]);
free(numbers);
numbers = NULL;
return 0;
}
Related functions
| Function | Purpose |
|---|---|
calloc | allocate and zero memory |
realloc | resize a block |
free | release a block |
Common bugs
- Memory leak: forgetting
free. - Double free: freeing the same pointer twice.
- Use after free: using memory after releasing it.
Where Teyro fits
Teyro's C for Beginners course turns this into short lessons you can play in a few minutes a day. It has 78 lessons, and you can start free.
The bottom line
Every malloc needs exactly one free.



