关于内存分配器的测试,首先是例子程序:
#include <stdio.h> #include <malloc.h> #if defined( USE_DL_MALLOC ) extern "C" void * dlmalloc( size_t ); extern "C" void dlfree( void * ); # define MALLOC dlmalloc # define FREE dlfree #else # define MALLOC malloc # define FREE free #endif struct Allocator { static void * operator new ( size_t space_length ) { printf( "acquare %u space\n" , space_length ); return MALLOC( space_length ); } static void operator delete ( void * space_pointer , size_t space_length ) { printf( "release %u space %p\n" , space_length , space_pointer ); FREE( space_pointer ); } static void * operator new [ ] ( size_t space_length ) { printf( "acquare %u array\n" , space_length ); return MALLOC( space_length ); } static void operator delete [ ] ( void * space_pointer , size_t space_length ) { printf( "release %u array %p\n" , space_length , space_pointer ); FREE( space_pointer ); } }; struct Matrix_1x4 : public Allocator { int X01 , X02 , X03 , X04 ; }; struct Matrix_4x4 : public Matrix_1x4 { int X11 , X12 , X13 , X14 ; int X21 , X22 , X23 , X24 ; int X31 , X32 , X33 , X34 ; }; struct Matrix_1x3 { int X01 , X02 , X03 ; }; struct Matrix_3x3 : public Matrix_1x3 , public Allocator { int X11 , X12 , X13 ; int X21 , X22 , X23 ; }; int main( int argc , char * argv[ ] ) { Matrix_1x4 * pArray1 = new Matrix_1x4[ 2 ]; Matrix_4x4 * pArray2 = new Matrix_4x4[ 2 ]; Matrix_1x3 * pArray3 = new Matrix_1x3[ 2 ]; Matrix_3x3 * pArray4 = new Matrix_3x3[ 2 ]; delete [ ] pArray1; delete [ ] pArray2; delete [ ] pArray3; delete [ ] pArray4; Matrix_1x4 * pMatrix1 = new Matrix_1x4; Matrix_4x4 * pMatrix2 = new Matrix_4x4; Matrix_1x3 * pMatrix3 = new Matrix_1x3; Matrix_3x3 * pMatrix4 = new Matrix_3x3; delete pMatrix1; delete pMatrix2; delete pMatrix3; delete pMatrix4; }
将该文件命名为 demo.cpp ,如果采用系统默认的分配器,则使用下面的命令行编译:
cl demo.cpp
然后执行 demo.exe 就可以看到结果,如果要测试使用 Doug Lea 的内存分配器,则使用如下的命令行编译:
cl demo.cpp dlmalloc.c /DUSE_DL_MALLOC
运行的结果应该是一致的,同时从运行结果可以看出在执行 delete 或者 delete[] 时,系统给的大小,应该是对象的 sizeof 的结果,即使数组也是如此,因此在 delete[] 中给出的大小仅仅是一个对象的大小,而不是整个数据占用内存空间的真实大小;
关于 Doug Lea 的 malloc 实现可以从这里获得,或者直接使用 ftp://g.oswego.edu/pub/misc/malloc.c 进行下载。