In C++, dynamic memory allocation is primarily done using the malloc function and new operators. Although they serve the same purpose, they differ in various aspects. The key distinction lies in the fact that new is an operator functioning as a construct, while malloc is a predefined standard library function found in the stdlib header file.
In this guide, we will explore the variance between using malloc and new in C++. Prior to delving into their distinctions, it's essential to understand the functionalities of malloc and new in the context of C++.
What is malloc?
In C++, the malloc function is primarily used for dynamic memory allocation during program execution. It yields a void pointer, enabling assignment to pointers of any type. This void pointer can be subsequently typecasted to access the memory location of a specific type.
Syntax
It has the following syntax:
type variable_name = (type *)malloc(sizeof(type));
In this syntax,
- type: It represents the data type of the variable for which the memory has to be allocated.
- variable_name: It defines the name of the variable thacpp tutorials to the memory.
- (type*): It is used for typecasting so that we can get the pointer of a specified type thacpp tutorials to the memory.
- sizeof: The sizeof operator is used in the malloc function to obtain the memory size required for the allocation.
Note: The malloc function returns the void pointer, so typecasting is required to assign a different type to the pointer. The sizeof operator is required in the malloc function as the malloc function returns the raw memory, so the sizeof operator will tell the malloc function how much memory is required for the allocation.
C++ Malloc Example
Let's consider a scenario to demonstrate the malloc function in C++.
Example
#include <iostream>
#include<stdlib.h>
using namespace std; //using standard namespace
int main() //main function
{
int len; // variable declaration
cout << "Enter the count of numbers : ";
cin >> len;
int *ptr; // pointer variable declaration
ptr=(int*) malloc(sizeof(int)*len); // allocating memory to the poiner variable
for(int i=0;i<len;i++)
{
cout << "Enter a number : ";
cin >> *(ptr+i);
}
cout << "Entered elements are : ";
for(int i=0;i<len;i++)
{
cout << *(ptr+i) << endl;
}
free(ptr);
return 0;
}
Output:
Enter the count of numbers : 4
Enter a number : 5
Enter a number : 6
Enter a number : 7
Enter a number : 8
Entered elements are : 5
6
7
8
Explanation:
In this illustration, we showcase the process of dynamic memory allocation utilizing the malloc function. Initially, the program prompts the user to input the quantity of elements desired, following which it reserves memory for the specified number of integers. Subsequently, we input the desired values which are then saved within the dynamically allocated array through pointer arithmetic.
What is new?
In C++, the new operator serves as a memory allocation operator, primarily employed for allocating memory dynamically during program execution. The memory allocated using the new operator is stored in the heap memory area. Upon execution, it provides the initial address of the allocated memory, which is then assigned to the respective variable. The new operator in C++ functions akin to the malloc function in the C programming language. Although C++ is compatible with the malloc function, the new operator is preferred due to its advantageous features.
Syntax
It has the following syntax:
type variable = new type(parameter_list);
In this syntax,
- type: It represents the datatype of the variable for which the memory is allocated by the new operator.
- new: It is an operator that is used to allocate the memory.
- variable: It is the name of the variable thacpp tutorials to the memory.
- parameter_list: It is the list of values that are initialized to a variable.
The new keyword does not rely on the sizeof function for memory allocation. Additionally, it does not require the use of resize since it allocates the exact amount of memory needed for an object. This operator is designed to invoke the constructor during declaration in order to initialize the object.
C++ New Operator Example
Let's consider an example to demonstrate the usage of the new operator in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
int *ptr; // integer pointer variable declaration
ptr=new int; // allocating memory to the pointer variable ptr.
cout << "Enter the number : " << endl;
cin >>*ptr;
cout << "Entered number is " <<*ptr<< endl;
return 0;
}
Output:
Enter the number :
18
Entered number is 18
Explanation:
In this instance, we showcase the new keyword which is utilized to dynamically reserve memory for a solitary integer. Initially, the software prompts the user to input a number which is then stored at the memory address indicated by ptr. Subsequently, the inputted value is displayed.
Main differences between malloc and new operator
Several main differences between malloc and new operator are as follows:
- The new operator constructs an object, i.e., it calls the constructor to initialize an object, while the malloc function does not call the constructor. The new operator invokes the constructor, and the delete operator invokes the destructor to destroy the object.
- The new is an operator, while malloc is a predefined function in the stdlib header file.
- The new operator can be overloaded, while the malloc function cannot be overloaded.
- If sufficient memory is not available in a heap, the new operator will throw an exception while the malloc function returns a NULL pointer.
- In the new operator, we need to specify the number of objects to be allocated. On the other hand, in the malloc function, we need to specify the number of bytes to be allocated.
- In the case of a new operator, we have to use the delete operator to deallocate the memory. But in the case of the malloc function, we have to use the free function to deallocate the memory.
- Once the memory is allocated using the new operator, then it cannot be resized. On the other hand, the memory is allocated using the malloc function; then, it can be reallocated using the realloc function.
- The execution time of new is less than the malloc function because new is a construct, and malloc is a function.
- The new operator does not return the separate pointer variable; it returns the address of the newly created object. On the other hand, the malloc function returns the void pointer, which can be further typecast in a specified type.
Difference between Malloc and new operator in Tabular Form
| malloc() | new Operator |
|---|---|
| Allocates memory without initializing it. | Allocates memory and initializes it. |
| Returns a void pointer that needs to be cast. | Returns a pointer of the specified type. |
| Cannot be overloaded. | Can be overloaded in C++. |
| Does not call constructors. | Calls constructors for objects allocated. |
| Requires manual memory deallocation. | Automatically releases memory when not needed. |
| Features | malloc() | new |
|---|---|---|
Type |
It is a library function of the C programming language. | It is an operator. |
| Constructor | This function does not call any constructor. | This function calls the constructors. |
| Overloading | It cannot be overloaded. | It can be overloaded. |
| Initialization | Memory initialization cannot be performed in malloc(). | It can initialize an object while allocating memory to it. |
| Returns | It returns void* (pointer). | It returns the data type. |
| Failure | When the malloc() function fails, it returns a NULL value. | When a new operator fails, it throws an exception. |
| Execution | It needs more time to execute applications. | It reduces the execution time of an application. |
| Reallocation | Memory allocated by the malloc() method can be reallocated using the realloc method. | It does not reallocate memory. |
Conclusion
In summary, the malloc function and the new operator serve the purpose of dynamically allocating memory during program execution. Nonetheless, these functions vary notably in their utilization and characteristics. While malloc is a C-style library function requiring manual typecasting and lacking constructor invocation, the new operator provides type safety, object-oriented capabilities, and automatic constructor invocation for objects.
Difference between malloc and new FAQs
1) What is the main difference between malloc and new in C++?
The primary contrast between malloc and new is that malloc functions as a library function in C, while new operates as an operator.
2) How is memory deallocated in malloc and new in C++?
Memory that is allocated using the malloc function should be deallocated using the free function. Conversely, memory allocated with the new operator should be released using the delete method.
3) Which one is more type-safe in malloc and new?
The new operator provides increased type safety by eliminating the need for explicit casting. In contrast, the malloc function lacks type safety as it returns a void* pointer.
4) Is there an exception for failure in C++?
When the malloc function encounters an error, it results in a NULL return value. Conversely, if the new operator encounters a failure, it raises a std::bad_alloc exception.
5) Which one should be used in C++?
Both functions are flexible and can be employed based on the user's needs. The new operator proves beneficial as it enables the use of constructors, ensures type-safety, and supports object-oriented characteristics. Conversely, the malloc function is predominantly used within the C programming language.