http://stackoverflow.com/questions/240212/what-is-the-difference-between-new-delete-and-malloc-free
being edited
|
C / malloc or
calloc and free
|
C++/ new /new []and
delete/delete[] |
Syntax : int n1 = (int *) malloc(sizeof(int));
free(n1);
|
Syntax :
int
*n1 = new int; delete(n1); // one object
int *n1 = new int[5] delete [] n1; // an array/vector |
|
|
- Allocates/release memory
- Allocating array requires manual calculation of
space.
- May throw NULL on failure
|
- Allocate/release memory
for an object from a pool called free-store.
- The compiler calculates the size.
- new operator will
not process a NULL (throws the bad_alloc on
failure)
- C++ uses ~destructor
function to destroy the object created with new
operator.
|
- malloc() returns a void pointer (void *), which
indicates that it is a pointer to a region of unknown
data type. The lack of a specific pointer type returned
from malloc is type-unsafe behavior, The function malloc allocates
the memories based on byte count but not on type.
|
- The new operators returns a
pointer to the newly allocated memory;
- new attempts to allocate enough memory on the
heap for the new data.
- In C++
new operator allows "Dynamic memory allocation", which
allows us to allocate memory of whatever size we want
when we need it on the fly.
|
- Reallocating larger chunk of memory simple. the
realloc() function change the size of a memory-block,
previously allocated with malloc() or calloc()
|
- In contrast to C/ realloc() function, it is not
possible to directly reallocate memory allocated with
new[] . To extend or reduce the size of a
block, one must allocate a new block of adequate size,
copy over the old memory, and delete the old block.
|
- .malloc/free can NOT be overridden legally
|
- operator new/delete can be overridden legally
- constructor/destructor used to initialize or destroy
the object
|
- The parameter or free(ch1) is a void pointer, frees
the memory hold-ups by calloc/realloc() functions.
|
- new add data on heap and may cause problem. Make
sure you need to use heap, or stack will do.
- When you use the new keyword you are putting data on
the heap. The heap is a large chunk of memory where
objects (which can be big in size) reside. The stack is
for simple data types like simple integers, chars etc
- A stack is a last-in, first-out (LIFO) structure.
|