malloc and free

The problem with fixed arrays

So far we made arrays "big enough", like int nums[100]. But what if the user needs 1,000 numbers? Or only 3? Fixed sizes either waste memory or are too small.

The solution: ask for exactly the memory you need, while the program is running. This is called dynamic memory.

Think of it like this: A fixed array is like booking a hall for 100 guests before you know who's coming. Dynamic memory is like counting your guests first, then booking a room of exactly the right size.

malloc: ask for memory

malloc ("memory allocate", from <stdlib.h>) reserves some bytes and gives you a pointer to them:

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

int main() {
    int n;
    scanf("%d", &n);

    int *nums = malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) {
        nums[i] = (i + 1) * 10;
    }
    for (int i = 0; i < n; i++) {
        printf("%d ", nums[i]);
    }
    printf("\n");

    free(nums);
    return 0;
}

Input (what the user types)

5

Output

10 20 30 40 50 
  • sizeof(int) is how many bytes one int needs (usually 4).
  • n * sizeof(int) is enough room for n ints.
  • malloc returns a pointer to the start. We use it just like an array: nums[i].
  • free(nums) gives the memory back when we're done.

Always free what you malloc

Memory from malloc stays reserved until you free it. If you forget, your program keeps eating memory – this is called a memory leak.

Remember: Every malloc needs exactly one free when you're finished with the memory.

Check that it worked

If there isn't enough memory, malloc returns NULL. Careful programs check:

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

int main() {
    double *prices = malloc(3 * sizeof(double));
    if (prices == NULL) {
        printf("Out of memory!\n");
        return 1;
    }
    prices[0] = 1.5;
    prices[1] = 2.25;
    prices[2] = 4.0;
    printf("Total: %.2f\n", prices[0] + prices[1] + prices[2]);
    free(prices);
    return 0;
}

Output

Total: 7.75
HOME LABS COMMUNITY DASHBOARD