malloc and free
Read · 1 of 4
Memory on request
int a[100]; has a fixed size. When the size comes from input, ask for exactly enough: int *a = malloc(n * sizeof(int)); (from <stdlib.h>). Use it like an array: a[i].
malloc returns NULL when there's no memory left; check for it. When you're finished, free(a); gives the memory back. Every malloc needs exactly one free.
Read this lesson as text
Arrays whose size you only know at run time.
Memory on request
int a[100]; has a fixed size. When the size comes from input, ask for exactly enough: int *a = malloc(n * sizeof(int)); (from <stdlib.h>). Use it like an array: a[i].
malloc returns NULL when there's no memory left; check for it. When you're finished, free(a); gives the memory back. Every malloc needs exactly one free.
An array sized by the input
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
scanf("%d", &n);
int *a = malloc(n * sizeof(int));
if (a == NULL) return 1;
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
printf("%d\n", a[0] + a[n - 1]);
free(a);
return 0;
}- Line 6: n is 3.
- Line 7: Ask for room for 3 ints (sizeof(int) bytes each). a points at the new block.
- Line 8: Got memory, so carry on.
- Line 9: Fill it like an array.
- Line 10: 5 + 4.
- Line 11: Give the block back. a must not be used after this.
Exercise: Any size, reversed
Read n (1 to 100000), then n numbers. Store them in memory from malloc, print them in reverse order separated by spaces, then free the memory.
Exercise: Growing with realloc
Read whole numbers until a 0 arrives; you don't know how many in advance.
Start with room for 2 and, whenever it's full, double it with a = realloc(a, cap * sizeof(int));. Print how many numbers came before the 0, then the numbers in reverse.