🎓 A1Learner
🔍
0 of 50 lessons completed

C Dynamic Memory

Dynamic memory is memory a program asks for while it runs. Pointers so far pointed at variables that already existed; malloc asks for fresh room while the program runs, and free gives it back.

Room for three numbers

The program asks for room for 3 ints. The check guards the NULL case, and the print shows 20, the middle number.

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

int main() {
  int *numbers = malloc(3 * sizeof(int));
  if (numbers == NULL) {
    printf("No memory.\n");
    return 1;
  }
  numbers[0] = 10;
  numbers[1] = 20;
  numbers[2] = 30;
  printf("%d\n", numbers[1]);
  free(numbers);
  return 0;
}

Ask for one number

The program asks for room for one int. It stores 77 there and prints 77, then gives the room back.

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

int main() {
  int *value = malloc(sizeof(int));
  if (value == NULL) {
    printf("No memory.\n");
    return 1;
  }
  *value = 77;
  printf("%d\n", *value);
  free(value);
  return 0;
}

Fill with a loop

The program asks for room for 4 ints. One loop fills each slot with 5, 10, 15, 20, and a second loop prints them.

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

int main() {
  int *numbers = malloc(4 * sizeof(int));
  if (numbers == NULL) {
    printf("No memory.\n");
    return 1;
  }
  for (int i = 0; i < 4; i++) {
    numbers[i] = (i + 1) * 5;
  }
  for (int i = 0; i < 4; i++) {
    printf("%d\n", numbers[i]);
  }
  free(numbers);
  return 0;
}

Example

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

int main() {
  int *scores = malloc(4 * sizeof(int));
  if (scores == NULL) {
    printf("No memory.\n");
    return 1;
  }
  scores[0] = 4;
  scores[1] = 8;
  scores[2] = 12;
  scores[3] = 16;
  int total = scores[0] + scores[1] + scores[2] + scores[3];
  printf("%d\n", total);
  free(scores);
  return 0;
}

Key points

  • Some programs do not know how much memory they need until they run.
  • The line #include <stdlib.h> brings in malloc and free.
  • malloc asks for a block of memory of a given size.
  • malloc(3 * sizeof(int)) asks for room for 3 ints.
  • sizeof(int) gives the size of one int.
  • malloc gives back the address of the block, or NULL when it cannot.
  • Always check the result against NULL before using the block.
  • Use the block like an array, with numbers[0], numbers[1], and so on.
  • free(numbers); gives the block back when it is no longer needed.

malloc asks for room for 4 ints. The check guards the NULL case. The program stores 4, 8, 12, and 16 in the block, adds them into total, and prints 40. The last line before return gives the block back with free.

Note

Never use the block after free, and never free the same block twice.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which line asks for room for 3 ints?