# 01.堆栈的深度问题

关于栈深度问题通常会出现在递归中。因为程序在递归时，每一层递归的临时变量和参数，都是被保存在栈中的，所以递归调用的深度过多，就会造成栈空间存储不足。一般来说栈是向下生长的，堆是向上生长的。把内存地址像门牌号编号成 1 \~ 10000，栈的使用就是先用第 10000 号内存块，再用第 9999 号内存块，依次减小编号。而堆的话，是先用第 1 号内存块，再用第 2 号内存块，依次增加编号。 堆内存可以认为是没有上限的（除非你的硬盘空间不足），如果消耗光了计算机的内存，操作系统还会用硬盘的虚拟内存为你提供更多的内存，虚拟内存和内存的读写速度几倍一致。但是如果大量程序占用了虚拟内存，很可能会出现内存泄露问题。这种情况，虚拟内存很快就会被消耗完毕。 栈内存不同于堆内存，通常编译器都会指定程序的栈内存空间使用的大小，如果栈内存使用超出了限制，就会触发程序异常退出，即栈溢出错误（Stack Over flow）。但是iOS实际开发中很少出现栈溢出问题，这就从侧面反映出使用的递归比较少。苹果官方文档指明：对于主线程，栈内存为 1 MB；非主线程，栈内存为 512 KB。如果想测试这一点，在主线程创建一个大小为100万的数组，这是Xcode就会报错。


---

# 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://ryukiedev.gitbook.io/wiki/ios/za-xiang/dui-zhan-de-shen-du-wen-ti.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.
