1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

What is the difference between malloc and new other than syntax?

Discussion in 'C' started by aspguy, May 16, 2008.

  1. aspguy

    aspguy New Member

    Joined:
    May 2, 2005
    Messages:
    59
    Likes Received:
    1
    Trophy Points:
    0
    What is the difference between malloc and new other than syntax?
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,293
    Likes Received:
    365
    Trophy Points:
    83
    The main differences are as follows

    1. Operator new constructs an object (calls constructor of object), malloc does not.

    2. Operator new is an operator and so it can be overloaded, where as malloc is a function.

    3. Implementation is different like new throws an exception if there is not enough memory, malloc returns a NULL.

    4. Operator new[] requires to specify the number of objects to allocate, malloc requires to specify the total number of bytes to allocate.

    5. malloc() returns void *, which has to be explicitly cast to the desired type but new returns the proper type.

    Apart from new / malloc in C++ there is no operator for realloc
     
  3. atul.sharma12

    atul.sharma12 New Member

    Joined:
    May 21, 2008
    Messages:
    15
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    S/W Engg.
    Location:
    This Planet only!!!!
    One more Difference..
    Memory allocated using Malloc can be resized using realloc.But It,s not possible in case of new.
     

Share This Page