×

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

Tower of Hanoi in C

What is Tower of Hanoi? The Tower of Hanoi is a gaming problem that was created in 1883 by a French mathematician named Édouard Lucas. The Tower of Hanoi temple in...

4 minutes read.

Pointer to pointer in C

A pointer to another pointer is another type of multiple indirections and a chain of many pointers. Generally, a pointer consists of the address of the variable. Once a pointer to...

4 minutes read.

Nested if-else statement in C

If we use an if-else statement within another if statement in a C program, it is called a nested if-else statement in C. It helps to check the condition inside...

3 minutes read.

strcat() Function in C

Strings in c: A string is defined as the set of characters that are enclosed within the double quotations (" "). The String always ends with the null character ("\0"). The...

3 minutes read.

Conio.h in C

Header files are the source files with the extension of .h. In c language header files are referred to as the helping files and they contain definitions of various functions...

4 minutes read.

Double Specifier in C

What is a double specifier? The term double denotes the double data type in C. It more accurately depicts floating point numbers. The idea that it has twice the precision of...

3 minutes read.

memcmp() in C

Introduction: In this article we are discuss about memcmp() function in C. This function permits the person to evaluate the bytes of the two characters, as mentioned above. Depending on...

4 minutes read.

10 Best IDEs for C or C++ Developers in 2024

Nobody can deny the fact that C and C++ were the first programming languages used by significant developers worldwide. Even now, newcomers who want to start programming are most frequently...

6 minutes read.

Difference between C and Java

C programming and Java programming are two of the earliest programming languages. C programming follows a procedural approach whereas Java programming follows an object-oriented approach. Java programming is a part...

3 minutes read.

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.

Kruskal algorithm in C

Given a weighted graph, Kruskal's algorithm generates a spanning tree with the lowest possible weights. Start by creating an edge list for the given graph, including the weights. Sort the...

3 minutes read.

Flexible Array Members in a Structure in C

There is flexibility to declare array from c99 generation onwards that declaration of the collections can be made possible without even mentioning its dimension, which means that the displays are...

4 minutes read.

#include in C

In the C programming language, #include is another way of inferring a standard, or a user defines file into the application or program. The preprocessor of the programming standard generally...

4 minutes read.

Snake Game in C

Snake game in C is basic desktop console program which was created in 1970’s. It is an old classic game which was played by every child across the world. This...

4 minutes read.

Segmentation Fault in C

Segmentation Fault in C In the C programming language, segmentation fault or segmentation violation or core dump is a condition that the hardware component raises to protect the memory by indicating...

4 minutes read.

Sum of N numbers in C using For loop

Before we move on the program of sum of N numbers, first we have to know about the For Loop statement. The syntax of ‘for’ loop in C programming language is...

3 minutes read.

Errors in C

Errors in C Errors are nothing but problems or faults that pretty much occur in all the programming languages. Errors make the behavior of the program seem abnormal, and even the...

4 minutes read.

Queue implementation in C

In the C programming language, the queue is the abstract concept that is similar to stacks. However, it is the part of the data structures that work opposite to that...

4 minutes read.

fgets() function in C

fgets() function is present in standard input and output library i.e, stdio.h library. It is a built-in function or pre-define function. It is used to read the specified stream from...

4 minutes read.

C Program of Fencing the Ground

The college's ground is rectangular. Fencing the ground the management makes the decision to construct a fence around the ground. They planned to wrap a thick rope around the ground...

1 minute read.