内存分配方式有三种:
(1)从静态存储区域分配。内存在程序编译的时候就已经分配好,这块内存在程序的整个运行期间都存在。例如全局变量,static变量。
(2)在栈上创建。在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时这些存储单元自动被释放。栈内存分配运算内置于处理器的指 令集中,效率很高,但是分配的内存容量有限。
(3) 从堆上分配,亦称动态内存分配。程序在运行的时候用malloc或new申请任意多少的内存,程序员自己负责在何时用free或delete释放内存。动 态内存的生存期由我们决定,使用非常灵活,但问题也最多。
#include <iostream> #include <stdio.h> using namespace std; //存在静态存储区。 int global1 = 1; int global2 = 2; int global3 = 3; int main() { //存在栈上。 int local1 = 4; int local2 = 5; int local3 = 6; //存在静态存储区。 static int static1 = 7; static int static2 = 8; static int static3 = 9; //存在堆上。 char *buf1 = new char[4]; char *buf2 = new char[4]; char *buf3 = new char[4]; cout << "&global1:" << &global1 << endl; cout << "&global2:" << &global2 << endl; cout << "&global3:" << &global3 << endl; cout << endl; cout << "&local1:" << &local1 << endl; cout << "&local2:" << &local2 << endl; cout << "&local3:" << &local3 << endl; cout << endl; cout << "&static1:" << &static1 << endl; cout << "&static2:" << &static2 << endl; cout << "&static3:" << &static3 << endl; cout << endl; printf("buf1:0x%08x\n", buf1); printf("buf2:0x%08x\n", buf2); printf("buf3:0x%08x\n", buf3); return 0; }
输出:
&global1:0x402000 &global2:0x402004 &global3:0x402008 &local1:0x22ff40 &local2:0x22ff3c &local3:0x22ff38 &static1:0x40200c &static2:0x402010 &static3:0x402014 buf1:0x003e3fe8 buf2:0x003e2470 buf3:0x003e2480
注意全局变量和静态变量分布在连续的内存空间!