free() in C - Source Code Example

In this source code example, we will see how to use the free() function in C programming with an example.

free() Function Overview

In C, dynamic memory allocation functions like malloc(), calloc(), and realloc() allow programmers to manually allocate memory during runtime. Once this memory has been used and is no longer needed, it should be returned to the system to avoid memory leaks. The free() function, found in the <stdlib.h> library does this. 

By giving the pointer that points to the allocated memory to free(), the memory is deallocated and given back to the system.

Source Code Example

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

int main() {
    int *arr;
    int n;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    // Using malloc to get memory for 'n' integers
    arr = (int*)malloc(n * sizeof(int));

    if (arr == NULL) {
        printf("Memory didn't get allocated!");
        exit(1);
    }

    printf("Put in %d integers:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // Showing the integers
    printf("The integers you entered:\n");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    // Giving back the memory
    free(arr);
    arr = NULL; // Good to set the pointer to NULL after giving back memory

    return 0;
}

Output

Enter number of elements: 4
Put in 4 integers:
10 20 30 40
The integers you entered:
10 20 30 40

Explanation

1. We ask how many integers the user wants to input.

2. Then we use malloc to get a space in memory for these numbers.

3. We check if the memory was given. If not, we show an error.

4. The user then puts in the integers, and we save them in the memory we got.

5. We show the user the numbers.

6. We use free to give the memory back. This is important so we don't waste memory.

7. It's a good idea to set the pointer to NULL after. 

This makes sure we don't accidentally use the memory.


Comments