关于 C/C++ 堆栈分配

About C/C++ stack allocation(关于 C/C++ 堆栈分配)
本文介绍了关于 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:

  1. 堆栈分配是否隐式调用 malloc/free 函数?如果不;如何保证栈分配和堆分配不冲突?

  1. 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++ 堆栈分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)