线程“< main>”使用Box分配大数组时已溢出其堆栈 [英] Thread '<main>' has overflowed its stack when allocating a large array using Box
问题描述
我正在实现 combsort 。我想在堆栈上创建固定大小的数组,但它显示堆栈溢出
。当我将其更改为在堆上时(以示例为例,Rust通过在堆中进行分配,我们必须使用 Box
),它仍然显示堆栈溢出
。
I'm implementing combsort. I'd like to create fixed-size array on the stack, but it shows stack overflow
. When I change it to be on the heap (Rust by Example says to allocate in the heap we must use Box
), it still shows stack overflow
.
fn new_gap(gap: usize) -> usize {
let ngap = ((gap as f64) / 1.3) as usize;
if ngap == 9 || ngap == 10 {
return 11;
}
if ngap < 1 {
return 1;
}
return ngap;
}
fn comb_sort(a: &mut Box<[f64]>) {
// previously: [f64]
let xlen = a.len();
let mut gap = xlen;
let mut swapped: bool;
let mut temp: f64;
loop {
swapped = false;
gap = new_gap(gap);
for i in 0..(xlen - gap) {
if a[i] > a[i + gap] {
swapped = true;
temp = a[i];
a[i] = a[i + gap];
a[i + gap] = temp;
}
}
if !(gap > 1 || swapped) {
break;
}
}
}
const N: usize = 10000000;
fn main() {
let mut arr: Box<[f64]> = Box::new([0.0; N]); // previously: [f64; N] = [0.0; N];
for z in 0..(N) {
arr[z] = (N - z) as f64;
}
comb_sort(&mut arr);
for z in 1..(N) {
if arr[z] < arr[z - 1] {
print!("!")
}
}
}
输出:
thread '<main>' has overflowed its stack
Illegal instruction (core dumped)
或
thread 'main' has overflowed its stack
fatal runtime error: stack overflow
我知道我的堆栈大小不够,与创建太大的非堆数组时的C ++相同函数内部,但此代码使用堆,但仍显示堆栈溢出。这段代码到底有什么问题?
I know that my stack size is not enough, the same as C++ when creating a non-heap array that is too big inside a function, but this code is using heap but still shows stack overflow. What's really wrong with this code?
推荐答案
据我所知,似乎该代码仍在尝试首先在堆栈上分配数组,然后然后将其移到框中。
As far as I can tell, it seems like that code is still trying to allocate the array on the stack first, and then move it into the box after.
如果我改换成 Vec< f64>
,对我有用的 Box< [f64]>
像这样:
It works for me if I switch to Vec<f64>
in place of Box<[f64]>
like this:
fn new_gap(gap: usize) -> usize {
let ngap = ((gap as f64) / 1.3) as usize;
if ngap == 9 || ngap == 10 {
return 11;
}
if ngap < 1 {
return 1;
}
return ngap;
}
fn comb_sort(a: &mut [f64]) {
// previously: [f64]
let xlen = a.len();
let mut gap = xlen;
let mut swapped: bool;
let mut temp: f64;
loop {
swapped = false;
gap = new_gap(gap);
for i in 0..(xlen - gap) {
if a[i] > a[i + gap] {
swapped = true;
temp = a[i];
a[i] = a[i + gap];
a[i + gap] = temp;
}
}
if !(gap > 1 || swapped) {
break;
}
}
}
const N: usize = 10000000;
fn main() {
let mut arr: Vec<f64> = std::iter::repeat(0.0).take(N).collect();
//let mut arr: Box<[f64]> = Box::new([0.0; N]); // previously: [f64; N] = [0.0; N];
for z in 0..(N) {
arr[z] = (N - z) as f64;
}
comb_sort(arr.as_mut_slice());
for z in 1..(N) {
if arr[z] < arr[z - 1] {
print!("!")
}
}
}
这篇关于线程“< main>”使用Box分配大数组时已溢出其堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!