{ }codelper

Reference › C

C malloc() and free(): Dynamic Memory

malloc allocates the number of bytes you ask for while the program runs and returns the address of the first one. Allocated memory does not disappear when a function ends. It stays until you give it back yourself with free. Both are in <stdlib.h>.

type *p = malloc(count * sizeof *p);
if (p == NULL) { /* allocation failed */ }
...
free(p);

Allocate the size you read from input

You pass malloc a number of bytes, not a number of elements. That is why you multiply by the size of one element, as in n * sizeof *a. If there isn't enough memory it returns NULL, so check for that, and give the memory back with free when you are done. Once it is allocated, you use it as a[i], just like an ordinary array.

#include <stdio.h>#include <stdlib.h> int main(void) {    int n;    if (scanf("%d", &n) != 1 || n <= 0) return 0;    int *a = malloc(n * sizeof *a);    if (a == NULL) return 1;    for (int i = 0; i < n; i++) a[i] = (i + 1) * (i + 1);    for (int i = 0; i < n; i++) printf("%d\n", a[i]);    free(a);    return 0;}
Input
4
Output
1
4
9
16

Edit and run it →

sizeof *a is "the size of one element that a points to". Writing sizeof(int) gives the same result, but this way there is only one place to fix if you change the type later.

calloc fills the memory with 0

The elements you get from malloc have unspecified contents. You must not read them before storing a value. calloc(count, size of one element) gives you elements that are all filled with 0. It suits an array you use for counting.

#include <stdio.h>#include <stdlib.h> int main(void) {    int *count = calloc(5, sizeof *count);    if (count == NULL) return 1;    count[2] += 3;    count[4]++;    for (int i = 0; i < 5; i++) printf("%d ", count[i]);    printf("\n");    free(count);    return 0;}
Output
0 0 3 0 1 

Edit and run it →

Change the size with realloc

realloc(p, new byte count) changes the size of allocated memory. If there isn't enough room, it moves the memory somewhere else and copies the contents for you, so you must use the new pointer it returns. If it fails, it returns NULL and the original memory stays as it was.

#include <stdio.h>#include <stdlib.h> int main(void) {    int *a = malloc(2 * sizeof *a);    if (a == NULL) return 1;    a[0] = 1; a[1] = 2;    int *t = realloc(a, 4 * sizeof *a);    if (t == NULL) { free(a); return 1; }    a = t;    a[2] = 3; a[3] = 4;    for (int i = 0; i < 4; i++) printf("%d\n", a[i]);    free(a);    return 0;}
Output
1
2
3
4

Edit and run it →

If you take the result directly with a = realloc(a, ...), then on failure a is overwritten with NULL and you have no way left to free the original memory. That is why the result goes into t first.

Create it in a function and return it

A local variable disappears when its function ends, but memory allocated with malloc stays. So a function can create an array and return it as a pointer. In exchange, whoever receives it is responsible for calling free.

#include <stdio.h>#include <stdlib.h> int *make_range(int n) {    int *a = malloc(n * sizeof *a);    if (a == NULL) return NULL;    for (int i = 0; i < n; i++) a[i] = i + 1;    return a;} int main(void) {    int *r = make_range(3);    if (r == NULL) return 1;    printf("%d %d %d\n", r[0], r[1], r[2]);    free(r);    return 0;}
Output
1 2 3

Edit and run it →

Common mistakes

Never calling free

for (int i = 0; i < 1000; i++) {
    int *buf = malloc(1000 * sizeof *buf);
    /* work with buf ... but there is no free(buf) */
}

→ The memory allocated on each pass is never given back and piles up (a memory leak). There is no error, so it is hard to notice

Each malloc or calloc goes with exactly one free. Call free(buf); before you lose the pointer (before you store another value in it or it goes out of scope).

Using freed memory again, or freeing it twice

int *a = malloc(3 * sizeof *a);
free(a);
a[0] = 7;    /* use after free */
free(a);     /* double free */

→ Both are undefined behavior. The program may look fine and then crash somewhere unrelated

Write a = NULL; right after free(a);. free(NULL) does nothing, so a double free is prevented, and using the pointer by mistake becomes easier to notice.

Not multiplying by sizeof

int n = 10;
int *a = malloc(n);   /* 10 bytes, not 10 elements */
for (int i = 0; i < n; i++) a[i] = i;

→ You allocate less than 10 int elements need, so the code writes past the allocated memory. This is undefined behavior

Always multiply by the size of one element, as in malloc(n * sizeof *a). Only for a char array, where one element is 1 byte, is malloc(n) right, and for a string you allocate strlen(s) + 1 to leave room for the \0.

Calling free on something that didn't come from malloc

int a[5];
int *p = a;
free(p);          /* not allocated memory */

int *q = malloc(5 * sizeof *q);
q++;
free(q);          /* not the exact address you received */

→ Both are undefined behavior

Pass free only the exact address that malloc, calloc, or realloc returned. Keep a separate pointer for walking through the memory, and keep the pointer you first received unchanged.

Practice problems

See also