学不会的 吸佳佳 -- 内存四区模型

笔记 / 2020-10-17

内存四区模型

    • 系统分配的内存,需要程序员手动释放
    • 局部变量,使用完毕后由操作系统自动释放
  • 常量区
    • 存放常量,通常是字符串常量
  • 静态区
    • 存放全局变量和静态变量

示例代码

#include <iostream>
using namespace std;

struct Result{
	Result(string m):msg(m){}
	string msg;
};
//global
int gHwnd = 0;

int main(){
	
	cout <<gHwnd <<endl<<
	"Addr : "<<&gHwnd<<endl;
	
	// heap 
	Result* r1 = new Result("HelloWorld!");
	cout <<r1->msg<<endl<<
	"Addr : "<<r1<<endl;
	delete(r1);
	
	// stack
	int errCode = 404;
	cout <<errCode<<endl<<
	"Addr : "<<&errCode<<endl; 
	
	// constant 
	const char* buffer = "Just do it.";
	cout <<*buffer<<endl<<
	"Addr : "<<buffer<<endl;
	
	// static
	static int exitCode = 0;
	cout <<exitCode<<endl<<
	"Addr : "<<&exitCode<<endl;
	
	return exitCode;
}