CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9
  1. #1
    Join Date
    Sep 2007
    Location
    Calcutta, India
    Posts
    95

    difference in malloc and new.

    As many would recognise, this is a common interview question.

    two differences I can think of are:

    1) new calls the constructor and malloc does not.

    2) new returns a pointer of the exact type of the object and malloc returns a void *.

    anyhing else to add?

    I

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: difference in malloc and new.

    Quote Originally Posted by indrajit_p1
    As many would recognise, this is a common interview question.

    two differences I can think of are:

    1) new calls the constructor and malloc does not.

    2) new returns a pointer of the exact type of the object and malloc returns a void *.
    3) "new" is a C++ operator, i.e. it is a keyword in C++, malloc() is a function call.

    4) Operator new/new[] must be followed somewhere by delete/delete[], malloc is paired with free()

    5) Operator new/new[] can be overloaded, malloc() cannot be overloaded.

    6) Operator new/new[] throws an exception if there is an error, malloc() returns a NULL pointer if there is an error.

    Regards,

    Paul McKenzie

  3. #3
    Join Date
    Oct 2006
    Location
    Singapore
    Posts
    346

    Re: difference in malloc and new.

    7) Initializers can be provided for non-arrays using new. The same cannot be done with malloc() (calloc() can be used for zero initialization).

    8) This one isn't really about malloc() but I thought it worth pointing out that memory allocated via malloc() can easily be reallocated using another library routine, realloc(). When using new this isn't directly possible. You have to allocate a different block of adequate size, copy the contents of the old block and finally deallocate the old block.
    Believe in your Dreams, Work for what you Believe in.
    My thoughts? Angelo's Stuff
    Some fun things I've done: RayWatch, QuickFeed, ACSVParser

    @ngelo

  4. #4
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: difference in malloc and new.

    9) The is "placement new" which allows you so specify WHERE to allocate the memory (useful especially in embedded systems to put an object at the location of a piece of hardware)

    10) You can implement different allocation schemes by providing type specific "operator new" implementations.

    11) "malloc" and "new" are both spelled and pronounced differently.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  5. #5
    Join Date
    Sep 2007
    Location
    Calcutta, India
    Posts
    95

    Re: difference in malloc and new.

    Quote Originally Posted by TheCPUWizard
    9)
    11) "malloc" and "new" are both spelled and pronounced differently.
    absolutely hillarious. :-D

    thanks a LOT for the inputs folks.
    I

  6. #6
    Join Date
    Aug 2005
    Location
    LI, NY
    Posts
    576

    Re: difference in malloc and new.

    Quote Originally Posted by angelorohit
    This one isn't really about malloc() but I thought it worth pointing out that memory allocated via malloc() can easily be reallocated using another library routine, realloc(). When using new this isn't directly possible. You have to allocate a different block of adequate size, copy the contents of the old block and finally deallocate the old block.
    Of course, this should not be used as a favorable argument for using malloc/realloc, but for using std::vector rather than new[].

    Quote Originally Posted by TheCPUWizard
    9) The is "placement new" which allows you so specify WHERE to allocate the memory (useful especially in embedded systems to put an object at the location of a piece of hardware)
    I don't know if "allocate" is the right term, since using placement new does not set aside the memory at that address per se. More accurately, I think, it constructs an object at a pre-allocated (or otherwise valid, if not on the heap) address.

    (I know you knew that, but I thought I should clarify the wording a bit.)
    - Alon

  7. #7
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: difference in malloc and new.

    Hermit, you are 100% correct. Thanks for the clarification.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  8. #8
    Join Date
    Sep 2007
    Posts
    62

    Re: difference in malloc and new.

    Quote Originally Posted by angelorohit
    7) Initializers can be provided for non-arrays using new. The same ....
    I think initializers can also be provided for arrays using new. Consider :

    Code:
    T *p = new T[num];
    If T is a user defined type with a default constructor which initializes the relevant (internal) variables, you are ok. However if T is a basic data type (like int) then initialization will not happen. To remedy this replace the statement above with the following :

    Code:
    T *p = new T[num] ();
    The following code illustrates the idea :

    Code:
    #include <iostream>
    using namespace std;
    
    const int num = 3;
    
    class a{
    private:
    	int i;
    public:
    	a(){i=10;}
    	friend ostream& operator<<(ostream& input_stream, const a &arg){
    		input_stream<<arg.i;
    		return input_stream;
    	}
    };
    
    template<typename T>
    void test0(){
    	T *p = new T[num];
    	for(int i=0; i<num; ++i){ cout<<*p<<endl;}
    	cout<<endl;
    }
    
    template<typename T>
    void test1(){
    	T *p = new T[num] ();
    	for(int i=0; i<num; ++i){ cout<<*p<<endl;}
    	cout<<endl;
    }
    
    int main()
    {
    	//Initializes only user defined types
    	test0<int>();
    	test0<a>();
    
    	//Initializes user and basic types
    	test1<int>();
    	test1<a>();
    
    	return 0;
    }
    This yields the following output :

    Code:
    -842150451
    -842150451
    -842150451
    
    10
    10
    10
    
    0
    0
    0
    
    10
    10
    10
    As we see test0<T> does not initialize correctly if T=int, whereas test1<T> does initialize correctly if T=int. Both these functions work fine for the user defined type "a".
    Last edited by artella; May 24th, 2008 at 08:24 AM.

  9. #9
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: difference in malloc and new.

    I think initializers can also be provided for arrays using new.
    I would say that is an edge case where you can value initialise with array new. You cannot, however, provide some other specific initial value with array new (according to the compiler I have at hand (g++ 4.2.3); my reading of the standard does not make things so clear).
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured