C Allocate Memory

In this lesson you will learn how to allocate memory while your program runs, using the malloc() and calloc() functions. This lets you store as much data as you need without deciding the amount in advance.

To allocate memory means to ask the system for a block of free space that your program can use. The most common function for this is malloc(), which stands for memory allocation. You tell it how many bytes you want, and it hands you a pointer to the start of that block.

Using malloc() and sizeof()

Because different data types take up different amounts of space, we use the sizeof operator to ask C how many bytes a type needs. Multiplying sizeof by the number of items gives the exact amount to request. This way your code works correctly no matter what computer it runs on.

Allocate space for an array of integers

#include <stdio.h>
#include <stdlib.h>

int main() {
    int count = 5;

    // Ask for room to hold 5 ints
    int *numbers = malloc(count * sizeof(int));
    if (numbers == NULL) {
        printf("Not enough memory!\n");
        return 1;
    }

    // Use it just like a normal array
    for (int i = 0; i < count; i++) {
        numbers[i] = i * 10;
        printf("%d\n", numbers[i]);
    }

    free(numbers);
    return 0;
}

One important detail: malloc() does not clean the memory it gives you, so it may contain leftover garbage values. If you want the memory to start out filled with zeros, use calloc() instead. calloc() takes two arguments: the number of items and the size of each item.

Allocate and zero memory with calloc()

#include <stdio.h>
#include <stdlib.h>

int main() {
    int count = 4;

    // Ask for 4 ints, all set to 0 automatically
    int *scores = calloc(count, sizeof(int));
    if (scores == NULL) {
        return 1;
    }

    // Every value is already 0
    for (int i = 0; i < count; i++) {
        printf("scores[%d] = %d\n", i, scores[i]);
    }

    free(scores);
    return 0;
}

Growing Memory with realloc()

  • realloc() lets you change the size of a block you already allocated, keeping the data that was there.
  • It is handy when you discover you need more room than you first asked for.
  • Always store the result of realloc() back into your pointer, because the block may move to a new location.
Note: Always check whether malloc(), calloc(), or realloc() returned NULL before using the memory. A NULL result means the request failed, and trying to use it will crash your program.
FunctionArgumentsStarts filled with zeros?
malloc()total bytesNo (garbage values)
calloc()count, size of eachYes
realloc()old pointer, new sizeKeeps old data