是否可以预测Linux上C语言中的堆栈溢出? [英] Is it possible to predict a stack overflow in C on Linux?
问题描述
在某些情况下,可能会导致x86 Linux系统上的堆栈溢出:
There are certain conditions that can cause stack overflows on an x86 Linux system:
-
堆栈上的
-
struct my_big_object[HUGE_NUMBER]
.经过它最终会导致SIGSEGV
. -
alloca()
例程(与malloc()
相似,但使用堆栈,自动释放自身,并且如果SIGSEGV
太大,则将其炸毁). 更新:我最初所说的alloca()并未被正式弃用;只是气.
struct my_big_object[HUGE_NUMBER]
on the stack. Walking through it eventually causesSIGSEGV
.- The
alloca()
routine (likemalloc()
, but uses the stack, automatically frees itself, and also blows up withSIGSEGV
if it's too big). Update: alloca() isn't formally deprecated as I originally stated; it is merely discouraged.
有没有一种方法可以以编程方式检测本地堆栈对于给定对象是否足够大?我知道堆栈大小可以通过ulimit
进行调整,所以我希望有一种方法(但是可能是不可移植的).理想情况下,我希望能够执行以下操作:
Is there a way to programmatically detect if the local stack is big enough for a given object? I know the stack size is adjustable via ulimit
, so I have hope there is a way (however non-portable it may be). Ideally, I would like to be able to do something like this:
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);
}
推荐答案
您可以通过查找进程的堆栈空间大小,然后减去使用的数量,来确定进程可用的堆栈空间.
You can determine the stack space the process has available by finding the size of a process' stack space and then subtracting the amount used.
ulimit -s
显示Linux系统上的堆栈大小.对于编程方法,请查看 getrlimit().然后,要确定当前的堆栈深度,请从一个堆栈的底部减去一个指向堆栈顶部的指针.例如(未经测试的代码):
shows the stack size on a linux system. For a programmatic approach, check out getrlimit(). Then, to determine the current stack depth, subtract a pointer to the top of the stack from one to the bottom. For example (code untested):
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;
}
这篇关于是否可以预测Linux上C语言中的堆栈溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!