free() Function with Example in C++

C++ free() function: Here, we are going to learn about the free() function with example of cstdlib header in C++ programming language.
Submitted by IncludeHelp, on May 28, 2020

C++ free() function

free() function is a library function of cstdlib header. It is used to deallocate the dynamically allocated memory blocks (i.e. the memory blocks allocated by the malloc(), calloc(), or realloc() functions) so that the memory blocks can be used for further allocations. It accepts a parameter which should be the pointer to the allocated memory.

Note: If the pointer does not point to the dynamically allocated memory it causes undefined behavior and if it is a null pointer, free() function does nothing.

Syntax of free() function:

C++11:

    void free (void* ptr);

Parameter(s):

  • ptr – represents a pointer to the dynamically allocated memory blocks.

Return value:

The return type of this function is void, It does not return anything.

Example:

    Input:
    // number of elements
    n = 5;

    // Dynamically allocate memory using malloc()
    ptr = (int*)malloc(n * sizeof(int));

    Function call:
    // freeing memory
    free(ptr);

C++ code to demonstrate the example of free() function

// C++ code to demonstrate the example of
// free() function

#include <iostream>
#include <cstdlib>
using namespace std;

// main() section
int main()
{
    int* ptr; // pointer
    int n, i;

    cout << "Enter number of elements: ";
    cin >> n;

    // Dynamically allocate memory using malloc()
    ptr = (int*)malloc(n * sizeof(int));

    // Check whether memory is allocated or not
    if (ptr == NULL) {
        cout << "Memory not allocated.." << endl;
        exit(EXIT_FAILURE);
    }
    else {
        cout << "Memory created..." << endl;

        // input array elements
        for (i = 0; i < n; ++i) {
            cout << "Enter element " << i + 1 << ": ";
            cin >> ptr[i];
        }

        // Print the array elements
        cout << "The array elements are: ";
        for (i = 0; i < n; ++i) {
            cout << ptr[i] << " ";
        }
        cout << endl;

        // freeing the memory
        free(ptr);
    }

    return 0;
}

Output

Enter number of elements: 5
Memory created...
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter element 5: 50
The array elements are: 10 20 30 40 50

Reference: C++ free() function




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.