Differences between new/delete and malloc/free in C and CPP

October 4th, 2011 by xrigher Leave a reply »

There is a very good post about this: http://www.codeproject.com/KB/tips/newandmalloc.aspx.

Here I’ll just list some of the differences concisely:

  • new & delete will call the object’s default constructor & destructor respectively; while malloc & free will not. This is also why dynamically array will call it’s element’s default constuctor. See http://liuweipingblog.cn/cpp/array-initialization-in-cpp/.
  • malloc returns a void*, so it’s result always needs cast. Such as: FooCls* t = (FooCls*) malloc(sizeof FooCls);
  • when using new to create an array, delete[] is needed. And never delete[] a single object, it's even worse.
  • realloc only exists with malloc/free pair. It's handy when resize an object to the same or less size.
  • new & delete are based on malloc & free. Malloc additionally allocate a header storing the size allocated, so free() knows the size to free. new[] not only keeps the malloc header, but also has an extra header storing the size of the array/vector, so delete[] knows how many objects are in the array/vector, and thus knows how many times to call the destructor.
    details of new[] & delete[] can be found at: Mismatching scalar and vector new and delete
Advertisement

Leave a Reply