C++ new[] 实际申请内存

来源:互联网 发布:伏安特性曲线实验数据 编辑:程序博客网 时间:2024/06/03 21:30
c++ 中使用new动态生成数组时,实际申请内存是否与期望值一样?如下面代码所示new int[count]申请内存是否等于len?
const int count = 10;const int len = sizeof(int) * count;int *array = new int[count]; 
编写测试代码如下。
#define TRACE(fmt, args...) printf("%s:%d " fmt, __FUNCTION__, __LINE__, ##args)class test{    public:        test(){printf("constructing test\n");};        ~test(){printf("destructing test\n");};        void *operator new[](size_t num){            TRACE("new[%d]\n", num);            return ::new char[num];        };        void operator delete[](void *ptr){            TRACE("delete[0X%X]\n", ptr);            ::delete []ptr;        };};int main(int argc, char **argv){    TRACE("sizeof class test: %d\n", sizeof(test));    test *pt = new test[8];    TRACE("address of pt: 0x%x\n", pt);    delete []pt;    return 0;}
现在执行程序,得到如下打印
main:61 sizeof class test: 1operator new []:50 new[12]    //实际申请多4个字节constructing testconstructing testconstructing testconstructing testconstructing testconstructing testconstructing testconstructing testmain:64 address of pt: 0x952900c //申请得到的地址destructing testdestructing testdestructing testdestructing testdestructing testdestructing testdestructing testdestructing testoperator delete []:54 delete[0X9529008] //申请与释放的地址不同
可以看到实际申请的内存比期望值多了4byte,同时可以注意到释放的地址=pt-4。那么这多申请的内存用在何处。接下来使用GDB调试,并在delete []pt;行打入断点。
gdb ./all(gdb) break 66Breakpoint 1 at 0x8048709: file main.cpp, line 66.
接下来我们执行程序,并打印pt指针的值,以及附近内存。
main:61 sizeof class test: 1operator new []:50 new[12]constructing testconstructing testconstructing testconstructing testconstructing testconstructing testconstructing testconstructing testmain:64 address of pt: 0x804b00cBreakpoint 1, main (argc=1, argv=0xbffff384) at main.cpp:6666              delete []pt;(gdb) p pt$3 = (test *) 0x804b00c(gdb) x/8xw 0X804B0080x804b008:      0x00000008      0x00000000      0x00000000      0x00020ff10x804b018:      0x00000000      0x00000000      0x00000000      0x00000000
可以看到在地址0x804b008,存放了一个数值8;也就是new test[8]中数组的大小。

其内存布局可以可以如下图所示。
这里写图片描述