Skip to main content
Logo image

Section 21.2 free() - Releasing Dynamically Allocated Memory

Recall that memory reserved dynamically via malloc() is completely your responsibility. Therefore, when you are done using the memory it is your job to tell the computer that you no longer need it and thus make available this memory for other purposes. The process of releasing memory is called freeing and we will now learn how to release, or free, memory that has been reserved via malloc() in the heap. The function to do so is called free() and it takes as an argument a pointer to the memory block that you’d like to release.
The prototype for free() is
void free(void *ptr);
The free() function also is a part of the standard library <stdlib.h> and you therefore need to
#include <stdlib.h>
(which you probably already did for the use of malloc().) The following video demonstrates the use of the free() function.

If you cannot see this codecast, please click here.

Check Your Understanding Check Your Understanding

1.

    Given the following code:
    #include <stdio.h>
    #include <stdlib.h>
    int main(void) {
      int *a, *b;
      float *c;
      a = (int *) malloc(sizeof(int));
      *a = 1;
      b = (int *) malloc(sizeof(int));
      *b = 2;
      free(a);
      free(b);
      c = (float *) malloc(sizeof(float));
      *c = 3.5;
      free(c);
      return 0;
    }
    
    What would the line
    printf("a = %d, b = %d, c = %f\n", *a, *b, *c);
    
    print to the screen if placed right before the return 0; line?
  • The result is unpredictable and may be different from one system to the next.
  • Correct
  • a = 1, b = 2, c = 3.5
  • Not quite. Try again!
  • a = 2, b = 2, c = 3.5
  • Not quite. Try again!
  • a = 2, b = 3, c = 3.5
  • Not quite. Try again!
  • a = 2, b = 3, c = 0.5
  • Not quite. Try again!