DSP

我理解的堆栈(stack)、动态内存分配与堆(heap)

2019-07-13 18:03发布

                   看到第4章,首次接触到堆(heap)这个概念,不好理解,所以用vs2010反汇编跟踪下程序: // use_new.cpp -- using the new operator #include int main() { using namespace std; int nights = 65535; int * ni = &nights; int * pt = new int; // new运算符为程序动态分配内存(程序运行时进行的),类似于C语言中的malloc函数 *pt = 65535; cout << "int nights value = " << nights // 从堆栈(stack)中取得数据65535 << ": location = " << &nights << endl; cout << "int* ni value = " << *ni // 从堆栈(stack)中取得ni值(地址[ni]),依照此(地址)在堆栈(stack)从寻找*ni中的数据65535 << ": location = " << ni << endl; cout << "int* pt value = " << *pt // 从堆栈(stack)中取得pt值(地址[pt]),依照此(地址)在堆(heap)从寻找*pt中的数据65535 << ": location = " << pt << endl; double * pd = new double; *pd = 10000001.0; cout << "double* pd value = " << *pd << ": location = " << pd << endl; cout << "location of pointer pt: " << &pt << "; location of pointer pd: " << &pd << endl; cout << "size of pt = " << sizeof(pt) << "; size of *pt = " << sizeof(*pt) << endl; cout << "size of pd = " << sizeof(pd) << "; size of *pd = " << sizeof(*pd) << endl; delete pt; // 与new运算符成对出现,释放new分配的内存空间。 delete pd; // 如果不用delete运算符,将发生内存泄露(被分配的内存再也无法使用了) return 0; } 1. 动态内存分配是指在程序运行时为程序中的变量分配内存空间,它完全由应用程序自己进行内存的分配和回收; 2. 变量nights、pt、pd的值都存储在被称为栈(stack)的内存区域中,这种存储数据方式便是“自动存储”;而new从被称为堆(heap)或自由存储区(free store)的内存池中分配内存,该内存池同静态变量与自动变量的内存是分开的,这种存储方式为“动态存储”;
3. Stack的内存管理是顺序分配的,而且定长,不存在内存回收问题;而Heap 则是随机分配内存,不定长度,存在内存分配和回收的问题; 跟踪如下: ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------