在什么时候内存通常分配给C ++中的局部变量? [英] At what moment is memory typically allocated for local variables in C++?

查看:270
本文介绍了在什么时候内存通常分配给C ++中的局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调试一个奇怪的堆栈溢出,据说是由于在堆栈上分配太大的变量,我想澄清以下。

I'm debugging a rather weird stack overflow supposedly caused by allocating too large variables on stack and I'd like to clarify the following.

假设我有以下函数:

void function()
{
    char buffer[1 * 1024];
    if( condition ) {
       char buffer[1 * 1024];
       doSomething( buffer, sizeof( buffer ) );
    } else {
       char buffer[512 * 1024];
       doSomething( buffer, sizeof( buffer ) );
    }
 }



我知道,这是编译器依赖,优化器决定什么,但是为这些局部变量分配内存的典型策略是什么?

一旦输入功能或将首先分配1千字节,则最坏情况(1 + 512千字节)将被立即分配,则根据条件,额外分配1或512千字节。

Will the worst case (1 + 512 kilobytes) be allocated immediately once function is entered or will 1 kilobyte be allocated first, then depending on condition either 1 or 512 kilobytes be additionally allocated?

推荐答案

您的本地(堆栈)变量分配在与堆栈框架相同的空间中。当函数被调用时,堆栈指针被改变为堆栈帧的换房间。它通常在单个调用中完成。如果你使用具有局部变量的堆栈,你会遇到堆栈溢出。

Your local (stack) variables are allocated in the same space as stack frames. When the function is called, the stack pointer is changed to "make room" for the stack frame. It's typically done in a single call. If you consume the stack with local variables, you'll encounter a stack overflow.

〜512 kbytes对于堆栈来说太大了。你应该使用 std :: vector 在堆上分配这个。

~512 kbytes is really too large for the stack in any case; you should allocate this on the heap using std::vector.

这篇关于在什么时候内存通常分配给C ++中的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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