New & Delete
New & Delete
New & Delete
new and delete operators are provided by C++ for runtime memory management. They
are used for dynamic allocation and freeing of memory while a program is running.
The new operator allocates memory and returns a pointer to the start of it. The delete
operator frees memory previously allocated using new. The general form of using them
is:
Question - Distinguish between new and malloc and delete and free().
Answer
Delete is assocated with new and free(0 is associated with malloc()
New
Its an operator
delete is associated with new
It creates an object
It throws exceptions if memory is unavailable
Operator new can be overloaded
You can state the number of objects to be created.
malloc()
It’s a function
free() is associated with malloc()
It does not create objects
It returns NULL
This cannot be overloaded
You need to specify the number of bytes to be allocated.
What is the difference between realloc() and free()?
An existing block of memory which was allocated by malloc() subroutine, will be freed
by free() subroutine. In case, an invalid pointer parameter is passed, unexpected results
will occur. If the parameter is a null pointer, then no action will occur.
Where as the realloc() subroutine allows the developer to change the block size of the
memory which was pointed to by the pointer parameter, to a specified bytes size through
size parameter and a new pointer to the block is returned. The pointer parameter specified
must have been created by using malloc(),calloc() or realloc() sub routines and should not
deallocated with realloc() or free() subroutines. If the pointer parameter is a null pointer,
then no action will occur.