3

Linux 是否在具有保证的最小大小的较低堆栈端下方提供不可访问的内存区域?如果存在这样的保证最小尺寸,它是什么?

或者换句话说,我什么时候应该开始担心alloca()给我指向有效的非堆栈内存的指针?

4

2 回答 2

4

As the alloca man page says:

There is no error indication if the stack frame cannot be extended. (However, after a failed allocation, the program is likely to receive a SIGSEGV signal if it attempts to access the unallocated space.)

So there is no indication at all and it also says:

If the allocation causes stack overflow, program behavior is undefined.

The stack overflow problem is a general issue with recursion and not really particular to alloca or let's say variable length arrays. Typically you either need to find a way to limit the depth of the recursion, refactor to an iterative solution or use your own dynamic stack(probably does not apply to this case).

Update

As the OP discovered Linux does provide an after the fact indication using a guard page after the stack of stack overflow by generating a SIGBUS signal, which addresses the first part of the question.

于 2014-03-20T17:44:13.000 回答
1

感谢@ElliottFrisch 让我用正确的名称在谷歌上搜索它......哎呀。

看起来答案是“在较新的内核中:一页,在较旧的内核中:没有这种保护”。

https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=320b2b8de12698082609ebbc1a17165727f4c893

于 2014-03-20T18:00:30.920 回答