×

Free() Function in C

Free() function is a built-in function which is define in the stdlib.h header file. If we want to use this function in our program, we must include the stdlib.h header file. The purpose of this function is to deallocate the memory block. The free() function is one of the functions in the concept called dynamic memory allocation. The memory allocated using malloc(), calloc() or realloc() functions is deallocated using free() function.

The function deallocates the memory and returns the memory to the heap. We need to deallocate memory because our computed contains a limited amount of memory, so we cannot run the infinite program in it. In the case of automatic allocation, the computer takes care of the free-up, but in the case of dynamic memory allocation, we need to free up the heap memory.

In C, the memory of a variable is deallocated automatically at compile time, but in the case of dynamic memory allocation, we need to deallocate the memory explicitly. In case we do not deallocate the memory, we may encounter out-of-memory errors. We have to free the memory because another process can use the use the same block of memory.

Syntax

void free( void *ptr);

ptr is the address of the memory block which has previously been allocated using malloc(), calloc() or realloc() function.

Parameter

The free () function takes a pointer variable as a parameter or the address of the memory, which we have to deallocate. Pointer variable is a variable which stores the address of another variable. We can pass only the address or pointer variable. We cannot pass ordinary variables or numerical values.

Return value

Free() function won't return any value. It deallocates or frees up the memory which has been previously allocated.

Example Programs on Implementation of Free() Function

// program to deallocate the memory using the free() function, which has previously allocated
#include<stdio.h>
#include <stdio.h>
int main() {
int* ptr; // declaring the pointer variable
ptr = malloc(10 * sizeof(*ptr)); // memory allocation to ptr using malloc() function 
// dynamically
if (ptr != NULL) // checking the memory is allocated or not
{
/* if the memory is allocated, then the ptr stores the address of the memory block, so we gave the condition as ptr ! = NULL */
  *(ptr) = 100; // Assigning the value to the memory block
// printing the assigned values to the memory block
  printf(" \nThe assigned to the memory block  is = %d",*(ptr)); 
}
free(ptr); // deallocating the memory of ptr using free() function.
}

Output:

Free() Function in C

Example 2:

// program to implement the free() function using calloc function
// program to read and print the array elements using dynamic memory allocation
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int* p; // pointer variable declaration
    int n; 
    printf(" \nEnter the size of the array: ");
    scanf("%d",&n); // reading the size of the array
    // allocating the memory using calloc() function
    p = (int*) calloc(n, sizeof(int)); 
    if(p == NULL) // checking whether memory is allocated or not
    {
        printf(" \nMemory not allocated \n");
    } // if
    else
    {
        printf(" \nMemory allocated successfully: "); 
        printf(" \nEnter the array Elements: ");
        // Reading the array elements
        for (int i=0; i<n; i++)
        {
            scanf("%d", &p[i]);
        }
        printf(" \nThe elements of the array are: ");
        // printing the array elements
        for (int i=0; i<n; i++)
        {
            printf("%d ", p[i]);
        } 
    } // else
    free(p); // deallocating the memory of p using free() function
    return 0;
} // main

Output:

Free() Function in C

Example 3:

// program to show the implementation of free() function in strings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () 
{
   char *ptr; // declaring the pointer variable
   // dynamic memory allocation to the ptr using malloc() function
   ptr = (char *) malloc(15); 
   strcpy(ptr, "JavaTpoint"); // copying the string in ptr using string handling function
   // printing the string and address of the memory block
   printf("String = %s,  Address = %u\n", ptr, ptr);
   /* Increasing the memory size by reallocating the memory using realloc() function */
   ptr = (char *) realloc(ptr, 25);
   strcat(ptr, ".com"); // adding .com to the string using string handling functions
   // printing the updated string and its address
   printf("String = %s,  Address = %u\n", ptr, ptr);
   /* Deallocate allocated memory */
   free(ptr);
   return(0);
}

Output:

Free() Function in C

If we see the output, both statements' address is different. By this, we can conclude that the address is not stable. It changes at every instance. If we run this program again we get another address.

Conclusion

In this article, we learned about the free() function in C, the detailed information of free() function parameter passing and return type in free() function. We discussed the syntax of the free() function. We did examples of the free() function and dynamic memory allocation, and deallocation of memory. Examples on free()  function using malloc(), calloc() and reallloc() function.


Related Topics

How to initialize array to zero in C

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.

abs() function in C

abs() function is a built-in function present in the stdlib.h header file. It returns an integer value. abs() function converts a negative value into a positive value. For example, if...

4 minutes read.

Array Example in C

An array is a collection of similar types of data elements arranged in such a way that any number of values can be assigned to it. It can store values that...

4 minutes read.

Structure Pointer in C

Structure Pointer in C In the C programming language, a structure pointer is defined as a pointer that points to the memory block address that stores a structure. Like C standard...

4 minutes read.

Decimal to Binary in C

What is a decimal number? A decimal number is a number represented in the decimal number system. This system of binary conversion uses base 10 to represent numbers, i.e. the digits...

3 minutes read.

Nested Structure in C

In C language, we can create nested Structure (Structure within Structure). There are two ways to define a nested structure. By separate structure By Embedded structure   Separate structure In a separate...

1 minute read.

fopen() function in C

fopen() function, is one of the file handling functions. It is used to open the existing file and perform operations on the file. If the file does not exist, it...

3 minutes read.

Bubble sort in C

Bubble sort in C Bubble sort is defined as the algorithm that is used for the sorting mechanism. It follows the technique of replacing the first index with the more minor...

4 minutes read.

C program to Store Information of Students Using Structure

What is the Structure in C? User-defined data types include structures. Structures aid your ability to combine things of various categories into a single group. Like arrays, it operates similarly. A...

3 minutes read.

Quick sort in C

Quick-sort, in the same way, like a merge sort, follows the principle of the divide and conquer algorithm. It then picks an element as pivot and partitions, and the given...

4 minutes read.

C Token

C Token and Keyword The C tokens are the basic buildings blocks in C language which are constructed together to write a C program. Each and every smallest individual unit in the C program is...

2 minutes read.

Goto and Labels in C

Introduction Goto in C: The goto statement is known as the jump statement in C. The goto is used to transfer the control of a program to a predefined label. The goto...

3 minutes read.

Variables in C

A variable can be defined as a name allocated to a storage space that can be manipulated by our programs. Every variable in C arbitrates about the overall layout and...

5 minutes read.

Write() function in c

As the name suggests the write () function is used to write the file descriptor. In other words it is used to write any file name without specifying file name,...

3 minutes read.

Find reverse of an array in C using functions

Introduction: Here, we describe how to find the reverse array in C using functions. Suppose you have an array with n elements. I need to display the elements present in...

3 minutes read.

Git Hooks

Git Hooks Overview Just like other version control systems, Git has its way to deliver customized scripts whenever some important activity occurs. The hooks act just like the triggers or catalysts...

4 minutes read.

C/C++ Program to Find the Size of int, float, double and char

In this tutorial, we will learn how to use the sizeof operator to determine the size of each variable. Program to Determine Variable Size Write a C or C++ program to determine the...

2 minutes read.

Header files in C

Header files in C In the C programming language, header files are present, which have an extension of ‘.h’, and it consists of macro definitions, declarations, and so on that are...

4 minutes read.

Big O Notation in C

Big O Notation in C: In the C programming language, we have so many algorithms and solutions to the problems that exist, which have different aspects and purposes to an...

3 minutes read.

Typedef vs define in C

Typedef VS define in C Typedef In the C programming language, a keyword called typedef can be used to give a type a new name. In other words, it is used to...

5 minutes read.