【问题标题】:Rust - Is the stack size different for debug vs. release mode?Rust - 调试与发布模式的堆栈大小是否不同?
【发布时间】:2021-04-29 09:44:55
【问题描述】:

考虑以下程序:

fn recursive_call(x: u32) -> u32 {
    println!("x: {:?}", x);
    recursive_call(x +1)
}

fn main() {
    recursive_call(0);
}

当我运行cargo build && ./target/debug/recursive_call 时,在x: 58152 之后崩溃:

x: 58152

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
Aborted (core dumped)

当我运行cargo build --release && ./target/release/recursive_call 时,它仅在x: 104728 之后崩溃:

x: 104728

thread 'main' has overflowed its stack
[...]

我想知道这种行为差异从何而来?发布与调试模式的堆栈大小是否不同?或者这是因为我缺少一些编译时优化(如果是,那么优化是什么?)

【问题讨论】:

    标签: rust stack-size


    【解决方案1】:

    是的,according to Godbolt 在 x86-64 上,调试模式下函数的保留堆栈大小为 120 字节,启用优化 (-O) 为 72 字节。这很正常。

    【讨论】:

      【解决方案2】:

      调试和发布的堆栈大小相同(除非您有线程,否则堆栈大小实际上是由操作系统固定的,参见例如 Linux 上的ulimit -s)。但是堆栈使用可能会有所不同,因为在调试模式下,编译器会向每个堆栈帧添加一些数据以帮助调试器找到局部变量。

      注意tail-call optimization may cause the compiler to remove the recursion 并允许在释放模式下无限循环。

      【讨论】:

        猜你喜欢
        • 2019-05-27
        • 2023-02-04
        • 1970-01-01
        • 2012-06-26
        • 2018-02-11
        • 1970-01-01
        • 2010-12-10
        • 2021-03-15
        • 1970-01-01
        相关资源
        最近更新 更多