×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

Difference between new and malloc() in C++

Learn: What are new and malloc() in C++ programming language, what are the differences between new operator and malloc() in C++?

In this post, we are going to learn about the new and malloc() in C++, what are the differences between new and malloc()?

What is malloc()?

malloc() is a library function of stdlib.h and it was used in C language to allocate memory for N blocks at run time, it can also be used in C++ programming language. Whenever a program needs memory to declare at run time we can use this function.

Example of malloc()

This program will declare memory for 5 integers at run time using malloc() function, read 5 numbers and print them.

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
	int *p; //pointer declaration
	int i=0;

	//allocating space for 5 integers
	p = (int*) malloc(sizeof(int)*5);

	cout<<"Enter elements :\n";
	for(i=0;i<5;i++)
		cin>>p[i];

	cout<<"Input elements are :\n";
	for(i=0;i<5;i++)
		cout<<p[i]<<endl;
	
	free(p);
	return 0;
}

Output

Enter elements :
10
20
30
40
50
Input elements are :
10
20
30
40
50

What is new?

new is an operator in C++ programming language, it is also used to declare memory for N blocks at run time.

Example of new

This program will declare memory for 5 integers at run time using new operator, read 5 numbers and print them.

#include <iostream>
using namespace std;

int main()
{
	int *p; //pointer declaration
	int i=0;

	//allocating space for 5 integers
	p = new int[5];

	cout<<"Enter elements :\n";
	for(i=0;i<5;i++)
		cin>>p[i];

	cout<<"Input elements are :\n";
	for(i=0;i<5;i++)
		cout<<p[i]<<endl;
	
	delete p;
	return 0;
}

Output

Enter elements :
10
20
30
40
50
Input elements are :
10
20
30
40
50

Differences between new operator and malloc() function in C++

Both are used for same purpose, but still they have some differences, the differences are:

  1. new is an operator whereas malloc() is a library function.
  2. new allocates memory and calls constructor for object initialization. But malloc() allocates memory and does not call constructor.
  3. Return type of new is exact data type while malloc() returns void*.
  4. new is faster than malloc() because an operator is always faster than a function.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.