new和delete

1.new和delete
程序的内存分为不同的区;
全局变量区中的变量在程序编译时决定,不需要管理内存;
局部变量一般存放在栈中,当用到时放入栈中,不用时栈中的地址处变成垃圾数据,也不需要管理;
而用malloc在堆中申请的内存在使用完后要调用free函数来释放;
 
1)关于malloc和free
malloc的函数调用链:
malloc    ->_nh_malloc_dbg    ->_heap_alloc_dbg    ->_heap_alloc_base    ->HeapAlloc
 
可以用反汇编追栈来分析:
 
HeapAlloc是kernel32.dll中导出的函数;
也可以直接调用该函数来申请堆内存,但是需要处理复杂的参数;
 
free的调用链:
free    ->_free_dbg       ->_free_base        ->HeapFree
 
free也是Kernel32.dll提供的;    
 
2)关于new和delete
如果想在堆中分配内存,也可以使用new
例如:
int* a = new int;
new的调用链:
new    ->_nh_malloc        ->_nh_malloc_dbg        ->_heap_alloc_dbg        ->_heap_alloc_base        ->HeapAlloc
可以看到new和malloc一样,最终都是调用kernel32.dll的HeapAlloc函数;
 
new申请的堆空间需要释放,在c++中可以用关键字delete;
void main(){
    int* a = new int;
    delete a;
    getchar();
}          
反汇编分析delete的函数调用链:
    delete    ->_free_dbg    ->...
后面不用看了,和free完全一样;
 
3)new和delete的使用
1】new 关键字                                int* pi = newint;                                
int* pk = new int(5);      //申请内存并赋初始值                          
                                
Person* ps = new Person;                                
Person* pd = new Person(1,2);    //申请内存并调用构造函数初始化    

第一步:_nh_malloc->_nh_malloc_dbg->_heap_alloc_dbg->_heap_alloc_base->HeapAlloc                                

第二步:调用构造函数                                
                                
2】delete关键字                                
delete pi;                                
delete pk;                                
第一步:调用析构函数                                
第二步:_free_dbg->_free_base->HeapFree                                
                                
3】new[] 与 delete[]的用法.                                
int* pi = new int[10];  //在堆中申请10个int空间                              
delete[] pi;                                          
                                
Person* p = new Person[2];                                
delete[] p;           //要释放多个对象的内存,需要调用多次析构函数,因此[]不能漏,否则只会调用一次析构函数,可以在对象的析构函数中加printf来验证               
原文地址:https://www.cnblogs.com/ShiningArmor/p/11956613.html