About C/C++ stack allocation(关于 C/C++ 堆栈分配)
问题描述
在学习 C++(和 C)时,我对堆栈分配的工作有一些特别的疑问,但我找不到解决方案:
While studying C++ (and C) I had some particular doubts regarding the working of stack allocation, that I can't find a solution to:
堆栈分配是否隐式调用 malloc/free 函数?如果不;如何保证栈分配和堆分配不冲突?
Does stack allocation call malloc/free functions implicitly? If not; how does it assure there is no conflict between stack allocation and heap allocation?
如果是的话;C++ 中的堆栈分配是否也隐式调用 new/delete?如果是;为一个类重载 new 运算符会影响它的堆栈分配吗?
If yes; does stack allocation in C++ implicitly call new/delete too? If yes; does overloading the new operator for a class affect its stack allocation?
它在 VC++ 中产生了令人困惑的结果;但由于 VC++ 并不完全符合标准(或者我听说过),我决定我最好在这里问...
It yielded confusing results in VC++; but as VC++ isn't entirely standard-compliant (or so I heard) I decided I better ask here...
推荐答案
堆栈分配不使用 malloc/free 之类的东西.它使用一块称为程序堆栈的内存,它只是一段连续的内存.
Stack allocation doesn't use anything like malloc/free. It uses a piece of memory called program stack which is just a contiguous segment of memory.
有一个特殊的寄存器存储栈顶.当在堆栈上创建新对象时,顶部会升高,从而增加堆栈,当对象被释放(超出范围)时,顶部会降低,从而减少堆栈.
There's a special register that stores the top of the stack. When a new object is created on stack the top is raised thus increasing the stack, when an object is deallocated (goes out of scope) the top is lowered thus decreasing the stack.
如果您尝试在堆栈上分配一个太大的对象或进行太深的递归,则顶部将超出堆栈允许的最大大小,这称为堆栈溢出.
If you try to allocate a too large object on stack or go too deep into recursion the top will outgrow the maximum allowed size of the stack and this is called stack overflow.
注意:堆栈增长的实际方向(增加或减少地址)会因系统而异,但无论实际方向如何,总体思路都是相同的.
Note: actual direction of stack growth (increasing or decreasing addresses) will vary by system, but general idea is the same regardless of actual direction.
这篇关于关于 C/C++ 堆栈分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:关于 C/C++ 堆栈分配
基础教程推荐
- 设计字符串本地化的最佳方法 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01