Malloc vs New: malloc and new operator in programming languages especially C++ is used to allocate space dynamically in memory (Heap). But both of them perform the same task in different ways. Let’s discuss the difference between malloc and new.
Malloc vs New
Malloc in C+ is a function which accepts size as an argument. Therefore malloc syntax usually looks like this:
int *array = (int*)malloc(4*sizeof(int)); // array of 4 Integers
free(array); //freeing up memory when the use of array pointer is finally over
- malloc returns untyped pointer i.e void*, therefore it needs to be typecaste into other pointer type explicitly.
- malloc return NULL if the memory allocation fails due to some reason.
- By using malloc for creating an object for class, the constructor doesn’t gets called.
- free() function is used to clear memory in heap.
- Use of free() function doesn’t call the destructor of the class.
New in C++ is an operator which is also used to allocate space in heap/free store for object or pointer. The syntax for new written like this.
int *array= new int;
delete array; //freeing up memory after the use of array pointer
- new return strictly typed pointer, hence it doesn’t require type casting.
- new does’t return NULL if the memory allocation fails, rather it will cause unwanted situations/errors in your program execution.
- Constructor gets called when we create object pointer using the new operator.
- delete command clears the memory taken by the pointer.
- Also, the destructor of the current object is called on using delete command.
- new operator doesn’t require explicit calculation of size for pointer creation.
delete array; //this statement will delete/clear only first element of the array
// i.e array
detele array; //this statement will clear whole array from the heap.
Using delete command on the object/pointer created using malloc and free() function on the object/pointer declared using new opearator is wrong and may cause an error or unwanted situation.
malloc function was introduced in C language and further new operator was introduced in C++. It means that the new operator is more efficient in dynamically allocating space in the heap.
Thats all for basic of new vs malloc. If you have any doubt then comment below.