问题描述
首先让我说我的问题不是关于堆栈溢出,而是在没有编译时错误的情况下实现它的警告。
我知道(第一手),您可以使用递归来溢出堆栈:
Let me start by saying my question is not about stack overflows but on way to make it happen, without compile-time errors\warnings.I know (first hand) you can overflow a stack with recursion:
void endlessRecursion()
{
int x = 1;
if(x) endlessRecursion(); //the 'if' is just to hush the compiler
}
我的问题是,是否有可能通过声明太多局部变量而使堆栈溢出。
显而易见的方法是声明一个大型数组,如下所示:
My question is, is it possible to overflow the stack by declaring too many local variables.The obvious way is just declare a huge array like so:
void myStackOverflow()
{
char maxedArrSize[0x3FFFFFFF]; // < 1GB, compiler didn't yell
}
实际上,即使0xFFFFF字节也会导致堆栈溢出我的机器
In practice even 0xFFFFF bytes causes stack overflow on my machine
所以,我想知道:
- 自从我没有尝试过,如果我声明足够的变量,
堆栈会溢出吗? - 是否可以使用预处理器或其他编译时工具(例如)来做第一件事,即通过某种方式使它声明很多局部变量它循环吗?如果是,怎么办?
- 这是理论上的-是否有办法知道程序的堆栈在编译时是否会溢出?
- Since I haven't tried it, if I declare enough variables would thestack overflow?
- Is there a way to use the preprocessor or other compile-time "tools" (like C++ template meta-programming) to do the first thing, i.e. make it declare a lot of local variables, by somehow causing it to loop? if so, how?
- This is theoretical - Is there a way to know if the a program's stack would overflow at compilation time? and if so, please explain.
推荐答案
是的,分配大量内存将导致堆栈溢出。分配一个大变量还是分配多个小变量都没关系;总大小是相关的。
Yes, allocating a large amount of memory will cause a stack overflow. It shouldn't matter whether you allocate one large variable or a lot of small ones; the total size is what's relevant.
您无法使用预处理器进行编译时循环,但是您可以实现一些捷径,使您可以生成大量代码无需全部输入。例如:
You can't do a compile-time loop with the preprocessor, but you can implement some shortcuts that let you generate large amounts of code without typing it all. For example:
#define DECLARE1 { int i;
#define END1 }
#define DECLARE2 DECLARE1 DECLARE1
#define END2 END1 END1
#define DECLARE4 DECLARE2 DECLARE2
#define END4 END2 END2
,依此类推。这会将多个 int i;
声明放入嵌套块中,确保所有对象同时存在,同时避免名称冲突。 (我想不出一种为所有变量赋予不同名称的方法。)
and so on. This puts the multiple int i;
declarations in nested blocks, ensuring that all the objects exist at the same time while avoiding name conflicts. (I couldn't think of a way to give all the variables distinct names.)
DECLARE4 END4
扩展为:
{ int i; { int i; { int i; { int i; } } } }
如果您的编译器对行长施加限制,则此方法将无效
This won't work if your compiler imposes a limit on the length of a line after preprocessing.
这里的教训是,预处理器并不是真正为这种事情设计的。用您喜欢的脚本语言编写生成声明的程序更加容易和灵活。例如,在bash中:
The lesson here is that the preprocessor isn't really designed for this kind of thing. It's much easier and more flexible to write a program in your favorite scripting language that generates the declarations. For example, in bash:
for i in {1..100} ; do
echo " int i$i;"
done
这篇关于局部变量堆栈溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!