Tuesday, May 6, 2014

malloc/free and new/delete in C++

malloc and free are C++/C language standard library functions, while new/delete are operator of C++. They can be used to allocate dynamic memory and free memory in C++ programs 

malloc/free can not meet the requirements of dynamic objects creation. Object needs to call the constructor to initialize the object when creating, the object needs to call the destructor before it is destroyed  Since malloc() and free() are library functions rather than operators, the compiler has no control permissions on them, so it can not impose the task of object construction and destruction on malloc() and free().

Therefore, C++ has an operator new to complete object dynamic memory allocation and object initialization, and an operator delete to clean up the object and release the memory allocated to the object. Note that the new/delete are not library functions.

Let's take a look at some codes to understand how malloc/free and new/delete to do object memory management.


class Obj 
{     
  public : 
          Obj(void){ cout << “Initialization” << endl; } 
          ~Obj(void){ cout << “Destroy” << endl; } 
          void    Initialize(void){ cout << “Initialization” << endl; }  
          void    Destroy(void){ cout << “Destroy” << endl; } 
  }; 
     
  void UseMallocFree(void)
  { 
      Obj  *a = (obj *)malloc(sizeof(obj));   // allocate memory
      a->Initialize();                                     // initialize
    
      //… 
    
      a->Destroy();   // clean up
      free(a);        // free allocated memory
  } 
     
  void UseNewDelete(void)  
  { 
    
      Obj  *a = new Obj;  // allocate memory and initialize
    
      //… 
    
      delete a;                   // clean up and free allocated memory

  }

Initialize() function in class Obj simulates the function of the constructor and Destroy() simulates the function of the destructor. In function UseMallocFree(). since malloc() and free() only take care of allocating and freeing memory, we need to call Initialize() and Destroy() to initialize the object and destroy the object. It's much simpler if we use UseNewDelete().

Since new/delete have all the functions of malloc/free, then why doesn't C++ rule out new/delete? This is because C++ programs need to call C functions frequently and C programs can only use malloc/free to manage dynamic objects.

If using free() to free the object created using new, then this object will produce error because it cannot call the destructor to destroy the object. If using delete to free the memory allocated with malloc(), theoretically the program will have no problem, but the readability is very poor. So we recommend to use new/delete as a pair and malloc/free as a pair as well.

No comments:

Post a Comment