malloc() vs new

programming

Summary: Both malloc() and new operator in C++ programming are used to dynamically allocate memory on the heap for variables and objects, but they differ in how they perform the task. Let’s discuss the difference between malloc and new.

Malloc() function

malloc() in C+ is a function that allocates memory for variables or objects on the heap.

It accepts size (memory space required by the variable) in bytes as an argument and returns a pointer to the allocated memory location.

The syntax for malloc() function is:

malloc(<size_in_bytes>)

Use sizeof() method to get size in bytes.

Properties of malloc() function

  • malloc() returns an untyped pointer (i.e. void*). The return type needs to be explicitly typecasted into the type of the object.
  • malloc() returns a null pointer if the memory allocation fails for some reason.
  • Creating an object using malloc() doesn’t invoke the constructor of the class.
  • Memory allocated by malloc() can be deallocated using the free() method.
  • The use of the free() method for destroying an object doesn’t invoke the destructor of the class.

Here is an C++ example, where we are creating an array of 4 elements using the malloc() function and printing the square of its elements.

// Online C++ compiler to run C++ program online
#include <iostream>
#include <math.h> 

int main() {
    // array of 4 Integers
    int n = 4;
    int *array = (int*)malloc(n*sizeof(int)); 
    
    //Input array
    std::cout << "Enter numbers: \n";
    for(int i=0; i<n; i++){
        std::cin >> array[i];
    }
    
    //Output square of array elements
    std::cout << "Square of numbers: \n";
    for(int i=0; i<n; i++){
        std::cout << pow(array[i], 2) << " ";
    }
    
    //free up memory when array pointer is no longer needed
    free(array); 
    return 0;
}

Output:

Enter numbers:
1 2 3 4
Square of numbers:
1 4 9 16


new operator

The new operator also allocates memory for variables or objects on the heap.

The new operator automatically calculates the size of the memory block for the given data type.

For multiple blocks of memory allocation (like in the case of an array), the number of memory blocks needed for allocation should be provided at object declaration.

The simple syntax for new operator is:

new type-name [initializer]

where initializer is optional and is the value for the initialized object.

Properties of new Operator

  • new operator returns strictly typed pointer. Hence it doesn’t require typecasting.
  • new doesn’t return a null pointer if the memory allocation fails, rather it returns zero or throws an exception.
  • When new is used to allocate memory for a C++ class object, the object’s constructor is called after the memory is allocated
  • Memory allocated by new can be deallocated using the delete operator.
  • The use of the delete operator on class objects also invokes the destructor of the class.

Here is a C++ example, where we are creating an array using the new operator and printing the cube of the array elements:

// Online C++ compiler to run C++ program online
#include <iostream>
#include <math.h>

int main() {
    //number of elements
    int n=4;
    //integer array
    int *array = new int[n];
    
    //Input numbers
    std::cout << "Enter numbers: \n";
    for(int i=0; i<n; i++){
        std::cin >> array[i];
    }
    
    //Output cube of the numbers
    std::cout << "Cube of numbers: \n";
    for(int i=0; i<n; i++){
        std::cout << pow(array[i], 3) << " ";
    }
    
    //Free up allocated memory
    delete[] array;
    return 0;
}

Output:

Enter numbers:
1 2 3 4
Cube of numbers:
1 8 27 64


Note: delete array will deallocate memory block for only the first element of the array. To deallocate the heap memory used by the whole array use delete[] array instead.

Difference between malloc() and new

malloc()new
Requires size for memory allocation.Requires the number of blocks for memory allocation.
Returns untyped pointer.Returns strictly typed pointer.
Doesn’t call the constructor for class objects.Calls constructor while allocating memory for class objects.
Allocated memory can be deallocated using free().Allocated memory can be deallocated using delete.
Returns a null pointer if the allocation fails.Throws an exception if memory allocation fails.

Using delete command on the object/pointer created using malloc and free() function on the object/pointer declared using the new operator is wrong and may cause an error or unwanted situation.

The ‘malloc function was introduced in C language, whereas the ‘new’ operator was introduced in C++.

In this tutorial, we learned with examples the properties and differences between malloc() function and new operator in C++ programming language.

Leave a Reply

Your email address will not be published. Required fields are marked *