C Programming: Memory, Pointers and the Stack ยท Dynamic Memory

Dynamic Memory: malloc and free

Ask for memory on the heap at run time, use it like an array, and give it back with free.

malloc_free.c

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

int main(void) {
    int n = 3;
    int *scores = malloc(n * sizeof(int));     /* memory on the heap, size chosen at run time */
    if (scores == NULL) {
        return 1;
    }
    for (int i = 0; i < n; i++) {
        scores[i] = (i + 1) * 10;
    }
    int total = scores[0] + scores[1] + scores[2];
    free(scores);                              /* give the memory back */
    scores = NULL;                             /* so it is not used by mistake */
    printf("%d\n", total);
    return 0;
}

Step by step

  1. n is created on the stack with the value 3.
  2. malloc reserves 3 ints on the heap and returns its address. Memory shows the new heap block.
  3. malloc returns NULL if there is no memory; always check.
  4. i is created on the stack with the value 0.
  5. Use the block like an array: scores[0] = 10.
  6. i changes from 0 to 1.
  7. In the int[3] that scores points to, index 1 changes from ? to 20.
  8. i changes from 1 to 2.
  9. In the int[3] that scores points to, index 2 changes from ? to 30.
  10. i goes out of scope and disappears.
  11. total is created on the stack with the value 60.
  12. free gives the block back. scores still holds the old address: a dangling pointer.
  13. Setting it to NULL makes the mistake impossible to miss.
  14. It prints 60.
  15. The method returns 0.
  16. 60. The heap block was created, used and released.