这个问题有点争议,看了很多博客,也去技术论坛搜了下,基本得出以下结论:malloc在堆上分配内存,new在自由存储区上分配内存。但是两者有何区别呢?
http://www.devx.com/tips/Tip/13757上所说:
The terms heap and free-store are used interchangeably(可交换) when referring to dynamically allocated objects. Are there any differences between the two?
Technically, free-store is an abstract term referring to unused memory that is available for dynamic allocations. Heap is the data model used by virtually(本质) all C++ compilers to implement the free-store. In practice, however, the distinction(区别) between heap and free-store is roughly(大致) equivalent(等价) to the differences between the memory models of C and C++, respectively.
In C, you allocate memory dynamically using malloc(), and release the allocated memory using free(). The allocated memory is not initialized. Dynamic allocations in C are said to take place on the heap.
In C++, you perform dynamic allocations with new and release the allocated memory with delete. Operator new automatically initializes the allocated memory (by calling the object’s constructor), and delete automatically destroys the object before releasing its memory. In C++, dynamic allocations are said to take place on the free-store.
Note that the heap and free-store may reside on(属于) distinct(不同) physical memory regions(区域) and they might be controlled by different underlying(潜在) memory managers(存储控制器).
http://www.gotw.ca/gotw/009.htm另外一个网站说:
Free Store
The free store is one of the two dynamic memory areas, allocated/freed by new/delete. Object lifetime can be less than the time the storage is allocated; that is, free store objects can have memory allocated without being immediately initialized, and can be destroyed without the memory being immediately deallocated. During the period when the storage is allocated but outside the object’s lifetime, the storage may be accessed and manipulated(篡改) through a void* but none of the proto-object(原型对象)’s nonstatic members or member functions may be accessed, have their addresses taken, or be otherwise manipulated.Heap
The heap is the other dynamic memory area, allocated/freed by malloc/free and their variants. Note that while the default global new and delete might be implemented in terms of malloc and free by a particular compiler, the heap is not the same as free store and memory allocated in one area cannot be safely deallocated in the other. Memory allocated from the heap can be used for objects of class type by placement-new construction and explicit destruction. If so used, the notes about free store object lifetime apply similarly here.