C++ Pointers malloc() vs new
Syntax of malloc() in C++
ptr = (cast-type*)malloc(byte-size);
Syntax of new operator in C++
ptr = new data-type;
Example of malloc() in C++
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int* ptr;
int n = 5;
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL) {
cout<<"Memory not allocated"<<endl;
exit(0);
} else {
cout<<"Memory allocated successfully"<<endl;
for (int i = 0; i < n; i++) {
ptr[i] = i + 1;
}
cout<<"The values of the array are: ";
for (int i = 0; i < n; i++) {
cout<<ptr[i]<<" ";
}
free(ptr);
}
return 0;
}
Output of malloc() in C++
Memory allocated successfully
The values of the array are: 1 2 3 4 5
Explanation of malloc() in C++
malloc
is used to allocate a block of memory of the specified size and returns a pointer of type void
, which can be cast to a pointer of any form.
Use of malloc() in C++
- It is fast and efficient for allocating large blocks of memory.
- It is useful when the size of memory to be allocated is not known until run time.
Important Points of malloc() in C++
- It does not call the class constructor.
- It is a function.
- It returns a
void
pointer.
Example of new operator in C++
#include <iostream>
using namespace std;
int main() {
int* ptr;
int n = 5;
ptr = new int[n];
if (ptr == NULL) {
cout<<"Memory not allocated"<<endl;
} else {
cout<<"Memory allocated successfully"<<endl;
for (int i = 0; i < n; i++) {
ptr[i] = i + 1;
}
cout<<"The values of the array are: ";
for (int i = 0; i < n; i++) {
cout<<ptr[i]<<" ";
}
delete [] ptr;
}
return 0;
}
Output of new operator in C++
Memory allocated successfully
The values of the array are: 1 2 3 4 5
Explanation of new operator in C++
The new
operator is used to allocate memory dynamically. It returns a pointer to the beginning of the memory block.
Use of new operator in C++
- It is useful for creating objects of classes.
- It can allocate memory for multiple objects of the same class.
Important Points of new operator in C++
- It calls the class constructor.
- It is an operator.
- It returns a pointer of the same type as the object being created.
Summary
Both malloc
and new
can be used to allocate memory dynamically in C++. However, new
is usually preferred as it calls the class constructor and returns a pointer of the same type as the object being created. malloc
returns a void
pointer and does not call the class constructor.