What is the difference between “new” and “malloc” and “calloc”
new/delete
- Allocate/release memory
- Memory allocated from 'Free Store'
- Returns a fully typed pointer.
- new (standard version) never returns a NULL (will throw on failure)
- Are called with Type-ID (compiler calculates the size)
- Has a version explicitly to handle arrays.
- Reallocating (to get more space) not handled intuitively (because of copy constructor).
- If they call malloc/free is implementation defined.
- Can add a new memory allocator to deal with low memory (set_new_handler)
- operator new/delete can be overridden legally
- constructor/destructor used to initialize/destroy the object
malloc/free
- Allocates/release memory
- Memory allocated from 'Heap'
- Returns a void*
- Returns NULL on failure
- Must specify the size required in bytes.
- Allocating array requires manual calculation of space.
- Reallocating larger chunk of memory simple (No copy constructor to worry about)
- They will NOT call new/delete
- No way to splice user code into the allocation sequence to help with low memory.
- malloc/free can NOT be overridden legally
malloc
in a function and new is an operator, and its a good programming
practice to use an operator instead of functions, because function
itself requires some time to be executed whenever that particular
function is called. so the main difference is that we use operators
instead of malloc because of the TIME CONSTRAINT.
1.malloc
requires the type casting during decleration , where as new doesn't
needed the type casting during decleration 2. when ever we use new for
allocating memory along with this it calls the constructor of the class
for which object memory is allocated 3. in case of malloc free is the
word used to clear the memory, where as delete is the format used in
case of new to free the memory after usage 4. malloc is function, where
as new is operator..so the time required for execution is less in case
of new (it being a operator) as compared to malloc(it being a function)
http://www.maxi-pedia.com/what+is+heap+and+stack
No comments:
Post a Comment