0

I've just heard that, C++ has two kinds of memory block that can be allocated and deallocated during runtime. It is said that, "malloc" and "free" use the memory called Free Memory Space, "new" and "delete" use the Heap.

Well, I wonder that what's the difference between Free Memory Space and Heap ?

Does the underlying implementation of C++'s operator new rely on C's malloc?

If "new" and "malloc" do use different memory block, then does the compiler have necessary for reserving a certain amount of memory for these two kinds of block (respectively) to prevent the memory allocated by "new" and the memory allocated by "malloc" from overlapping ?

Zhiwei Chen
  • 312
  • 2
  • 11
  • Possible duplicate: http://stackoverflow.com/questions/240212/what-is-the-difference-between-new-delete-and-malloc-free – felixgaal Sep 07 '13 at 07:56
  • See this http://stackoverflow.com/questions/6161235/what-is-the-difference-between-the-heap-and-the-free-store. I think you probably are reading the old Herb Sutter documentation of http://www.gotw.ca/gotw/009.htm which has a difference between free store and heap – bjackfly Sep 07 '13 at 07:59

2 Answers2

0

Where memory is allocated from is implementation and library dependent. The C++ language doesn't specify it.

The underlying library responsible for the low level allocation used by malloc/free and new/delete is usually (if not always) the same.

Memory allocated by it is commonly either from the heap or using mmap.

jlliagre
  • 29,783
  • 6
  • 61
  • 72
0

Both new and malloc eventually request memory blocks from the kernel so there's no "specific memory area" for one that the other cannot use. However when you free memory with delete or free the code needs to do some checks and release the chunks back to the kernel correctly.

The difference comes from accounting. For example one issue is what to do with very small allocations. I.e. you don't want to request a kernel memory chunk just to store a bool. There are some optimizations so that this works efficiently and the optimizations are different between malloc and new.

Sorin
  • 11,863
  • 22
  • 26
  • `new` and `malloc` do not necessarily request memory from the kernel. Depending on the size requested, the memory might have already be requested by the library before the call. `free` and `delete` are not required to release memory back to the kernel. This is implementation dependent. – jlliagre Sep 07 '13 at 15:40