Monday, April 2, 2012

What is the difference between malloc and new?

This is the regular question generally you will get in C++ Interviews. Both new and malloc are used to allocate the dynamic memory. malloc is used in C and new is used in C++. And the basci difference is new calls the constructor to allocate the memory whereas malloc() is itself is a function and it wont call the  constructor. Lets see the differences.

  • This is a function
  • It will return the void pointer.
  • Need to type cast to the required data type.
  • It returns NULL if there is no enough memory.
  • It works in C and C++
  • need to use free to deallocate the memory
  • This cann't be overleaded
  • syntax:
               void *malloc(size_t size)

  • example:
  • int *ptr;
    ptr = (int *)malloc(10*sizeof(int));  // allocationg 10 bytes of int type
    //do something
    free(ptr); // deallocating the memory

  • new is an operator.
  • It calls the constructor while allocating the memory and destructor while deallocating the memory
  • It will return required pointer data type
  • No need to type cast
  • It will return bad exception when there is no enough memory
  • It works only in C++
  • Need to use delete for deallocating the memory
  • its possible to overload the new operator
  • Syntax:
            ptr = new typename; 
where ptr is pointer of typename(generally class name).
  • example:
  • int *p;
    p = new int; // allocating int datatype
    //do something
    delete p; // for deallocating the memory

No comments:

Popular Posts