Tom*_*Tom 4 c linux x86 alloca
某些条件可能导致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);
}
Run Code Online (Sandbox Code Playgroud)
您可以通过查找进程堆栈空间的大小然后减去使用的数量来确定进程可用的堆栈空间.
ulimit -s
Run Code Online (Sandbox Code Playgroud)
显示了linux系统上的堆栈大小.对于程序化方法,请查看getrlimit().然后,要确定当前堆栈深度,请从一个到底部减去指向堆栈顶部的指针.例如(代码未经测试):
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;
}
Run Code Online (Sandbox Code Playgroud)