在 x86 Linux 系统上,某些情况会导致堆栈溢出:
struct my_big_object[HUGE_NUMBER]
在堆栈上。遍历它最终导致SIGSEGV
。alloca()
例程(类似于malloc()
,但使用堆栈,自动释放自身,并且还会因SIGSEGV
而爆炸如果太大)。 更新:alloca() 并没有像我最初所说的那样被正式弃用;只是气馁。
有没有办法以编程方式检测本地堆栈对于给定对象是否足够大?我知道堆栈大小可以通过 ulimit
进行调整,所以我希望有一种方法(但它可能是不可移植的)。理想情况下,我希望能够做这样的事情:
int min_stack_space_available = /* ??? */;
if (object_size < min_stack_space_available)
{
char *foo = alloca(object_size);
do_stuff(foo);
}
else
{
char *foo = malloc(object_size);
do_stuff(foo);
free(foo);
}
最佳答案
您可以通过查找进程堆栈空间的大小然后减去已用量来确定进程可用的堆栈空间。
ulimit -s
显示 linux 系统上的堆栈大小。对于编程方法,请查看 getrlimit() .然后,要确定当前堆栈深度,从 1 到堆栈底部减去指向堆栈顶部的指针。例如(代码未经测试):
unsigned char *bottom_of_stack_ptr;
void call_function(int argc, char *argv) {
unsigned char top_of_stack;
unsigned int depth = (&top_of_stack > bottom_of_stack_ptr) ?
&top_of_stack-bottom_of_stack_ptr :
bottom_of_stack_ptr-&top_of_stack;
if( depth+100 < PROGRAMMATICALLY_DETERMINED_STACK_SIZE ) {
...
}
}
int main(int argc, char *argv) {
unsigned char bottom_of_stack;
bottom_of_stack_ptr = &bottom_of_stack;
my_function();
return 0;
}
关于c - 是否可以在 Linux 上预测 C 中的堆栈溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/427209/