C free() Function Complete Tutorial

In this section, we will learn what the free() function is and how to use it in C.

Note: we’re assuming you are familiar with malloc() and calloc() functions.

Free Memory in C: free() Function

The memories that are allocated via the call to either `malloc()` or `calloc()` functions will stay allocated as long as the program is running.

Note: These types of allocated memories are in a place called the Heap.

But for the majority of times, we don’t need an allocated memory to stay allocated for the entirety of a program’s execution time!

For example, we might have an array of integers and after a few calls to some functions in the program, we might not need that array anymore.

In such case, it’s a good idea to deallocate the memory space and let other programs in the system to use that memory if they need too.

So in order to deallocate such memory space, we use the `free()` function.

Note: the prototype of the `free()` function exists in the `stdlib.h` header file and so we need to include the header file in order to use the function.

C free() Function Syntax:

Here’s the prototype of the function:

void free(void *ptr)

C free() Function Parameters:

This function takes one argument and that is the address of the starting point of the memory-space that is allocated via the call to the `malloc` or `calloc` function.

C free() Function Return Value:

The function doesn’t return a value.

Example: free malloc in C via free() function

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

int main() {

    int *pointer = (int *) malloc(10* sizeof(int));

    for (int i = 0; i<10; i++){
        *(pointer+i) = i;
    }
    for (int i = 0; i<10; i++){
        printf("%d, ",*(pointer+i));
    }
    free(pointer);
    return 0;
}

Output:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9,

Note: This function only accepts the address of those memories that are allocated via the call to `malloc` or `calloc` function. If we set the address of other types of memory, we will get an error instead.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies