In this chapter of C++ interview questions, we will learn about:
-
malloc in c++ and malloc syntax
-
new in c++ and new syntax
-
malloc vs new in c++
To provide flexibility to the programmers, Dynamic Memory Allocation(DMA) is an important concept.
It allocates memory in the Heap. Its application is wide like you can use for variable-length array as well for Data Structures like a linked list, tree.
C uses calloc() and malloc() for DMA.
C++ also has this along with new & delete operators for allocating and free memory.
Unused memory needs to be de-allocated otherwise there will be a Memory Leak issue
Lets learn a bit more about malloc and new in c++ along with their syntax.
Malloc() in C++
malloc() in C++ is a library function used for allocating memory dynamically.
Malloc() in C++:
-
allocates a block of memory, but doesn't initialize.
-
and returns a pointer of void.
malloc syntax
ptr =(datatype*) malloc(size);
New in C++
New in C++ is an operator used to request for memory allocation.
If memory is free,
-
new operator initializes memory and
-
returns the address of new allocated space.
new syntax
pointer_var = new datatype;
Difference between malloc and new
Lets see the difference between malloc and new in c++.
Serial No.
|
malloc()
|
new
|
1
|
malloc() doesn’t call constructor
|
new calls constructor
|
2
|
malloc() is a function
|
new is a operator
|
3
|
malloc() returns void pointer
|
new returns same data type
|
4
|
On failure condition it returns NULL
|
It returns bad_allocation
|
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Page Views :
Published Date :
Jan 24,2021