Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C Dynamic Memory: malloc and calloc

Arrays have a fixed size, chosen when you write the program. Often the size is only known when the program runs: how many students will the user type in? Dynamic memory is memory you ask for while the program runs, as much as you need.

malloc

malloc(bytes) from stdlib.h reserves a block of memory and returns a pointer to it. Multiply the number of elements by sizeof one element to get the size. When there is not enough memory it returns NULL, so check before using it.

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

int main(void) {
    int n = 5;
    int *squares = malloc(n * sizeof(int));
    if (squares == NULL) {
        printf("Not enough memory\n");
        return 1;
    }
    for (int i = 0; i < n; i++) {
        squares[i] = (i + 1) * (i + 1);   // use it like an array
    }
    for (int i = 0; i < n; i++) {
        printf("%d ", squares[i]);
    }
    printf("\n");
    free(squares);                        // give the memory back
    return 0;
}
Output
1 4 9 16 25 

The size from the user

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

int main(void) {
    int n;
    printf("How many numbers? ");
    if (scanf("%d", &n) != 1 || n <= 0) return 1;
    double *values = malloc(n * sizeof *values);
    if (values == NULL) return 1;
    double sum = 0;
    for (int i = 0; i < n; i++) {
        scanf("%lf", &values[i]);
        sum += values[i];
    }
    printf("Average of %d numbers: %.2f\n", n, sum / n);
    free(values);
    return 0;
}
You type
3
4
8
9
Output
How many numbers? Average of 3 numbers: 7.00

sizeof *values is the size of what values points at. It stays right even if the type of values changes later.

calloc

calloc(count, size) reserves memory for count elements and sets every byte to zero. malloc leaves the memory as it was, full of old values.

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

int main(void) {
    int *counts = calloc(5, sizeof(int));
    if (counts == NULL) return 1;
    counts[2] = 7;
    for (int i = 0; i < 5; i++) printf("%d ", counts[i]);
    printf("\n");
    free(counts);
    return 0;
}
Output
0 0 7 0 0 

Stack and heap

Ordinary local variables live on the stack: they are created when a function starts and disappear when it returns. Memory from malloc lives on the heap: it stays until you call free, even after the function that asked for it returns. That is what makes it useful, and why you must remember to free it. The next topic covers realloc, free and memory leaks.

Practice exercises

  1. Ask the user how many marks they will type, store them in memory from malloc, and print the highest.
  2. Create a copy of a string in new memory: allocate strlen(s) + 1 bytes and use strcpy.
  3. Use calloc to count how many times each digit 0 to 9 appears in a number the user types.