Smart Recent Blog Post List

Sep 11, 2011

new vs malloc ?

C++ often confuses beginners with its multiple way to allocate and free memory. Most of them understand them that free must be used with malloc and delete with new. But still they are not clear with the differences. This article will help in understanding the concept behind new and malloc.

Lets see the broader level differences first :-


  •  'new' helps in constructing an object (calls constructor), malloc does not. One of the most important differences between them.
           e.g. Consider a
           Class A { 
           public : A() { cout <<"In constructor"; }
           }
           
          A* pobjA =  new A(); //this will call constructor and displays "In constructor"
          A* pa       = (A*) malloc(sizeof(A));  //this will not call constructor
  • new requires type of object to be allocated, malloc requires you to specify the total number of bytes to allocate.
  • operator new is an operator, malloc is a function.
  • operator new throws an exception if there is not enough memory, malloc returns a NULL.                   As both function help allocating memory dynamically, there are chances for run-time failure due to non availability of memory. For such cases both shows different behavior and hence need to be handled accordingly.
          very important pint to be noticed over here is
When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated.
  • operator new can be overloaded, malloc cannot be overloaded.
  • operator new/new[] must be matched with operator delete/delete[] to deallocate memory, malloc() must be matched with free() to deallocate memory.
Another big question is

How to choose between malloc and new ?

While working with C++, its always recommended to use "new", because it has additive advantage over malloc which are:-
  • Its type safe.
  • It calls constructor and helps in implementing very important Object Oriented feature Inheritence (constructor chaining). 
One can though use malloc while working with buffer (non class and struct base) , which they want to resize with time with the help of realloc. But still it can be achieved with the combination new/delete too.

How much one can allocate ?

One more query one can have now is, "How much one can allocate"? The largest possible memory block malloc can allocate depends on the host system, particularly the size of physical memory and the operating system implementation. Theoretically, the largest number should be the maximum value that can be held in a size_t type, which is an implementation-dependent unsigned integer representing the size of an area of memory. The maximum value is 2power(CHAR_BIT*sizeof(size_t) − 1), or the constant SIZE_MAX in the C99 standard.

More relevant article:-





1 comments:

Post a Comment

Smart Recent Blog Post List