可执行程序看起来好像占据了一个连续的内存块,称为“程序映像”。程序映像有几个不同的分区。程序文本或者代码显示在低位内存中。已初始化和未初始化的静态变量在映像中有自己的分区。其他分区堆,堆栈和环境。
活动记录:是在进程堆栈顶部分配的一个内存块,用于保存调用过程中函数的执行上下文。每个函数调用都会在堆栈上创建一个新活动记录。函数返回时就会将活动记录从堆栈中删除,为嵌套的函数调用提供“最后被调用的最先被返回”
虽然程序映像看起来好像占用了一个连续的内存块,但实际上操作系统将程序映像映射到不连续的物理内存中。常见的映射将程序映像分成大小相同的片。称为页(Page)。操作系统将这些页加载到内存中。当处理器引用该页的内存时,就从一个表中查找页的位置。这种映射允许这些堆栈和堆在不实际使用物理内存的情况下有很大的逻辑地址空间。操作系统隐藏这种底层映射的存在。因此程序员可以将程序映像看成逻辑上连续的。即便是一些页并没有驻留在内存中。
On most systems, malloc calls operating system services to map pages into the the process address space to create and expand the memory pool. If you call malloc, and no memory is available, most implementations will call a system service to map more memory and expand the pool.
As shown above, the stack segment is near the top of memory with high address. Every time a function is called, the machine allocates some stack memory for it. When a new local variables is declared, more stack memory is allocated for that function to store the variable. Such allocations make the stack grow downwards. After the function returns, the stack memory of this function is deallocated, which means all local variables become invalid. The allocation and deallocation for stack memory is automatically done. The variables allocated on the stack are called stack variables, or automatic variables.
In the previous section we saw that functions cannot return pointers of stack variables. To solve this issue, you can either return by copy, or put the value at somewhere more permanent than stack memory. Heap memory is such a place. Unlike stack memory, heap memory is allocated explicitly by programmers and it won’t be deallocated until it is explicitly freed. To allocate heap memory in C++, use the keyword new
followed by the constructor of what you want to allocate. The return value of new
operator will be the address of what you just created (which points to somewhere in the heap).