malloc() function in C++

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

1. malloc() Function Overview

The malloc() function is used to allocate a specified size of memory during the execution of a program. The memory allocated by malloc() remains until it's either freed by the programmer using the free() function or until the program terminates. It's part of the C standard library <cstdlib> in C++ and is often used in C++ programs for memory allocation in scenarios where dynamic allocation is needed.

Signature:

void* malloc(size_t size);

Parameters:

- size: The number of bytes to allocate.

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));

    if(arr == NULL) {
        std::cerr << "Memory allocation failed." << std::endl;
        return 1;
    }

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

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

    // Free the allocated memory
    free(arr);

    return 0;
}

Output:

1 2 3 4 5

3. Explanation

1. We declare an integer pointer named arr to hold the address of the first byte of allocated memory.

2. Using malloc(), we dynamically allocate memory for 5 integers.

3. We then check if memory allocation was successful by comparing arr to NULL.

4. We assign values to the allocated memory and then print the contents.

5. After we're done with the dynamically allocated memory, we release it using the free() function.


Comments