free() function in C++

In this guide, you will learn what is free() function is in C++ programming and how to use it with an example.

1. free() Function Overview

The free() function in C++ is used to deallocate the memory that was previously allocated by malloc(), calloc(), or realloc() functions. It is crucial to free up memory in C++ programs that make use of dynamic memory allocation to prevent memory leaks. The free() function releases the memory and returns it to the system for reuse. It's included in the C standard library <cstdlib> in C++.

Signature:

void free(void* ptr);

Parameters:

- ptr: A pointer to the memory block that was previously allocated. If ptr is NULL, no action occurs.

2. Source Code Example

#include <iostream>
#include <cstdlib>

int main() {
    int* arr;
    int n = 5; // Number of integers

    // Dynamically allocate memory for 5 integers using malloc
    arr = (int*) malloc(n * sizeof(int));

    // Assign values to the dynamically allocated memory
    for(int i = 0; i < n; i++) {
        arr[i] = i * 10;
    }

    // Print the values
    for(int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }

    std::cout << std::endl;

    // Free the allocated memory
    free(arr);

    // It's good practice to set pointer to NULL after freeing
    arr = NULL;

    return 0;
}

Output:

0 10 20 30 40

3. Explanation

1. We start by dynamically allocating memory for an array of 5 integers using malloc().

2. We then assign values to this memory.

3. We print the contents of the dynamically allocated array.

4. After utilizing the dynamically allocated memory, we release it using the free() function. This is important to prevent memory leaks.

5. Lastly, setting the pointer to NULL after freeing is a best practice to ensure we don't accidentally use the pointer again, as it no longer points to valid memory (this helps to avoid "dangling pointer" issues).


Comments