top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

what is difference between new and malloc ??

+4 votes
133 views

what is difference between new and malloc ??

posted Oct 21, 2013 by Vikas Upadhyay

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

2 Answers

+3 votes
 
Best answer

The main difference between new and malloc is that new invokes the object's constructor and the corresponding call to delete invokes the object's destructor.
Also 'new' is only available in C++. malloc() is available in both C and C++.
There are other differences:
1. new is type-safe, malloc returns objects of type void*
2. new throws an exception on error, malloc returns NULL and sets errno
3. new is an operator and can be overloaded, malloc is a function and cannot be overloaded
4. new[], which allocates arrays, is more intuitive and type-safe than malloc
5. malloc-derived allocations can be resized via realloc, new-derived allocations cannot be resized
6. malloc can allocate an N-byte chunk of memory, new must be asked to allocate an array of, say, char types

answer Oct 22, 2013 by Satyabrata Mahapatra
+2 votes

new is the C++ implementation of the memory allocation while malloc is the way of allocation in C.

  • malloc allocates uninitialized memory. The allocated memory has to be released with free. (calloc is like malloc but initializes the allocated memory with a constant (0))
  • new initializes the allocated memory by calling the constructor (if it's an object). Memory allocated with new should be released with delete (which in turn calls the destructor). It does not need you to manually specify the size you need and cast it to the appropriate type. Thus, it's more modern and less prone to errors.
answer Oct 22, 2013 by Bob Wise
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...