C++ malloc() Function

The malloc() function is a commonly used function in the C++ programming language. It is used to dynamically allocate memory during runtime. The malloc() function allocates a block of memory of the specified size and returns a pointer to the beginning of that block.

Here is the syntax of the malloc() function:

void* malloc(size_t size);

The malloc() function takes a single argument, which is the number of bytes to allocate. It returns a pointer of type void* to the allocated memory if the allocation is successful. If the allocation fails, it returns a NULL pointer.

Let’s look at some examples to understand how to use the malloc() function:

Example 1: Allocating Memory for an Integer

#include <iostream>
#include <cstdlib>

int main() {
    int* ptr = (int*)malloc(sizeof(int));
    
    if (ptr != NULL) {
        *ptr = 42;
        std::cout << "Value: " << *ptr << std::endl;
        free(ptr);
    }
    
    return 0;
}

In this example, we allocate memory for an integer using the malloc() function. We cast the returned pointer to an int* type to indicate that it points to an integer. We then assign a value of 42 to the allocated memory and print it. Finally, we free the allocated memory using the free() function.

Example 2: Allocating Memory for an Array of Doubles

#include <iostream>
#include <cstdlib>

int main() {
    int size = 5;
    double* arr = (double*)malloc(size * sizeof(double));
    
    if (arr != NULL) {
        for (int i = 0; i < size; i++) {
            arr[i] = i * 1.5;
        }
        
        std::cout << "Array: ";
        for (int i = 0; i < size; i++) {
            std::cout << arr[i] << " ";
        }
        std::cout << std::endl;
        
        free(arr);
    }
    
    return 0;
}

In this example, we allocate memory for an array of doubles using the malloc() function. We again cast the returned pointer to a double* type. We then initialize the array with values using a loop and print the array. Finally, we free the allocated memory using the free() function.

It is important to note that when using malloc(), you must manually free the allocated memory using the free() function to avoid memory leaks. If you forget to free the memory, it can lead to memory leaks and potential performance issues.

Additionally, it is worth mentioning that in modern C++, it is generally recommended to use the new operator instead of malloc() for dynamic memory allocation. The new operator not only allocates memory but also calls the constructor of the object, providing safer and more convenient memory management.

In conclusion, the malloc() function in C++ is used to dynamically allocate memory during runtime. It is a powerful tool for managing memory when used correctly. However, it is important to free the allocated memory using the free() function to prevent memory leaks.

Scroll to Top