这个Rust代码为什么在没有递归或循环的情况下会导致堆栈溢出?

huangapple go评论67阅读模式
英文:

Why does this Rust code cause a stack overflow without recursion or looping?

问题

无法弄清楚为什么这段Rust代码会导致栈溢出。

enum SlidingAttackTable {
    Rook([[u64; 4096]; 64]),
    Bishop([[u64; 512]; 64]),
}

fn init_all() -> (SlidingAttackTable, SlidingAttackTable, [u64; 64], [u64; 64], [usize; 64]) {
    return (SlidingAttackTable::Bishop([[0; 512]; 64]), SlidingAttackTable::Rook([[0; 4096]; 64]), [0; 64], [0; 64], [0; 64]);
}

fn main() {
    println!("start");
    let (bishop_attack_table, rook_attack_table, bishop_masks, bishop_magic_numbers, bishop_relevant_bits) = init_all();
}

我已尝试将除了println!("start")之外的所有内容都注释掉,它打印了"start"而没有出现错误。不知何故,当我添加回这几行代码时,甚至在执行该行并打印"start"之前就崩溃了。我无法检测到任何循环或递归,因此不知从何开始诊断这个问题。

英文:

I cannot figure out why this Rust code causes a stack overflow.

enum SlidingAttackTable {
    Rook([[u64; 4096]; 64]),
    Bishop([[u64; 512]; 64]),
}

fn init_all() -> (SlidingAttackTable, SlidingAttackTable, [u64; 64], [u64; 64], [usize; 64]) {
    return (SlidingAttackTable::Bishop([[0; 512]; 64]), SlidingAttackTable::Rook([[0; 4096]; 64]), [0; 64], [0; 64], [0; 64]);
}

fn main() {
    println!("start");
    let (bishop_attack_table, rook_attack_table, bishop_masks, bishop_magic_numbers, bishop_relevant_bits) = init_all();
}

I have tried commenting out everything but println!("start") and it printed "start" with no error. Somehow, when I add just these few lines of code back in, it crashes before even getting to that line and printing "start". There is no looping or recursion going on here that I can detect, so I have no idea how to begin diagnosing this problem.

答案1

得分: 4

[u64; 4096] 占据2^(3+12)字节。这是2^15字节。
[[u64; 4096]; 64] 占据其64倍(即2^21字节,或2 MB)。看起来你已经达到了堆栈大小限制。

你可以增加堆栈大小的限制,但这可能不是一个好主意。总的来说,不应该尝试在堆栈上保留太多数据。应该使用堆。有多种方法可以实现这一点。如果你正在使用 vector,那么堆栈上只会持有一个指针,而数据本身将位于堆上。

英文:

[u64; 4096] takes 2^(3+12) bytes. That's 2^15 bytes.
And [[u64; 4096]; 64] takes 64 times of that (i.e. 2^21 bytes, or 2 MB). It seems you have hit the stack size limit.

You could increase the stack size limit, but that would probably be a bad idea. Overall, you shouldn't try to keep too much data on the stack. Use the heap instead. There are multiple ways to do that. If you are using a vector, only a pointer will be held on the stack and the data itself will be on the heap.

huangapple
  • 本文由 发表于 2023年6月5日 01:46:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401685.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定