关于 C/C++ 堆栈分配 [英] About C/C++ stack allocation

查看:34
本文介绍了关于 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++ 堆栈分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆