简体   繁体   English

堆栈溢出大数组但不是同样大的向量?

[英]Stack overflow with large array but not with equally large vector?

I ran into a funny issue today working with large data structures. 今天我遇到了一个有趣的问题,处理大型数据结构。 I initially was using a vector to store upwards of 1000000 ints but later decided I didn't actually need the dynamic functionality of the vector (I was reserving 1000000 spots as soon as it was declared anyway) and it would be beneficial to, instead, be able to add values any place in the data structure. 我最初使用一个向量来存储超过1000000的整数但后来决定我实际上并不需要向量的动态功能(无论如何我一直保留1000000个点),相反,它将是有益的。能够在数据结构中的任何位置添加值。 So I switched it to an array and BAM stack overflow. 所以我把它切换到一个数组并且BAM堆栈溢出。 I'm guessing this is because declaring the size of the array at compile time puts it in the stack and making use of a dynamic vector instead placed it on the heap (which I'm guessing is larger?). 我猜这是因为在编译时声明数组的大小会将其放入堆栈并使用动态向量而不是将其放在堆上(我猜它更大?)。

So what's the right answer here? 那么这里的答案是正确的? Move back to a dynamic memory system just so it gets put on the heap? 回到动态内存系统只是为了把它放到堆上? Increase the size of the stack? 增加堆栈的大小? Or am I way off base on the whole thing here...? 或者我在这里基于整个事情... ...

Thanks! 谢谢!

I initially was using a vector to store upwards of 1000000 ints 我最初使用矢量来存储超过1000000的整数

Good idea. 好主意。

but later decided I didn't actually need the dynamic functionality of the vector (I was reserving 1000000 spots as soon as it was declared anyway) 但后来决定我实际上并不需要矢量的动态功能(无论如何我一直保留1000000个点)

Not such a good idea. 不是一个好主意。 You did need it. 你确实需要它。

and it would be beneficial to, instead, be able to add values any place in the data structure. 相反,能够在数据结构中的任何位置添加值将是有益的。

I don't follow. 我不跟随。

I'm guessing this is because declaring the size of the array at compile time puts it in the stack and making use of a dynamic vector instead placed it on the heap (which I'm guessing is larger?). 我猜这是因为在编译时声明数组的大小会将其放入堆栈并使用动态向量而不是将其放在堆上(我猜它更大?)。

Much. 许多。 The call stack is typically of the order of 1MB-2MB in size by default. 默认情况下,调用堆栈的大小通常为1MB-2MB。 Your "heap" (free store) is only really bounded by your available RAM. 你的“堆”(免费商店)只受你可用内存的限制。

So what's the right answer here? 那么这里的答案是正确的? Move back to a dynamic memory system just so it gets put on the heap? 回到动态内存系统只是为了把它放到堆上?

Yes. 是。

[edit: Joachim's right — static is another possible answer.] [编辑:约阿希姆的权利 - static是另一个可能的答案。]

Increase the size of the stack? 增加堆栈的大小?

You could but even if you could stretch 4MB out of it, you've left yourself no wiggle room for other local data variables. 你可以,但即使你可以伸出4MB,你也没有为其他本地数据变量留下空间。 Best use dynamic memory — that's the appropriate thing to do. 最好使用动态内存 - 这是适当的事情。

Or am I way off base on the whole thing here...? 或者我在这里基于整个事情... ...

No. 没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM