Posts Tagged ‘memory’

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

October 4th, 2011

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

c++ vector memory taken

March 2nd, 2010

Here is a experiment about how much memory will a vector array take with different size on a 64bit machine with a 64bit OS (Ubuntu).

Vector Arr Size   Memory
10K * 1             208K
10K * 10           688K
10K * 100         5.4M
10K * 1000       52.8M
12K * 100         12.3M
100K * 10         10M
300K * 10         30M
300K * 100        158M

Note: 10K * 1 means an array of 10K vectors with each vector having 1 int element.