# C++内存模型

## C++内存分为5个区域：

* 堆内存：由new分配的内存块，其释放编译器不去管，而是由我们程序自己控制，一个new对应一个delete。如果没有释放掉，在程序运行结束时操作系统也会自动回收。涉及的问题：缓冲区溢出，内存泄漏。
* 栈内存：在需要时分配，存放局部变量，函数参数，存放在这栈中的数据只在当前函数及下一层函数中有效，一旦函数返回了，这些数据也就自动释放掉了。
* 全局/静态存储区：全局和静态变量被分配到同一块内存中。
* 常量存储区：存放常量，不允许被修改。
* 代码区：存放代码（如函数），不允许修改，但可以执行。

## C++内存模型为：

* 自由存储区：局部非静态变量的存储区域，就是栈。
* 动态区：用operator new, malloc分配的内存，就是堆。
* 静态区：全局变量，静态变量，字符串常量存放的位置。

代码虽占内存，但不属于C++内存模型的一部分。

## 在linux系统中，程序在内存中的分布如下所示：

从 低地址-->高地址 代码区--> 全局/静态存储区-->堆--> unused -->栈-->env


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jun-wang.gitbook.io/learnjava/bian-cheng-yu-yan/c++/c++-nei-cun-mo-xing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
