gpt4 book ai didi

c - 是否可以在 Linux 上预测 C 中的堆栈溢出?

转载 作者:IT王子 更新时间:2023-10-29 00:56:37 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com