我正在 x86 架构中编写一个程序(由于技术原因我无法使用 x64)。我设计的程序使用的 RAM 内存低于 4GB。但是,当我为大型 std::vector
分配内存时,我注意到构造函数分配的内存超过了所需的内存,然后将内存削减到适当的数量(在较小的内存需求上进行了测试,以便能够观察)。这是一个问题,因为分配的 RAM 多于所需的 RAM 的短暂时刻会由于 > 4GB RAM 使用而导致程序崩溃。
有没有办法阻止程序动态分配超过给定数量的 RAM?如果是这样,如何在 Visual Studio 解决方案中设置此属性?
I am writing a program in x86 architecture (for technical reasons I cannot use x64). I have designed my program such that it uses under 4GB of RAM memory. However, when I allocate memory for large std::vector
s I notice that the constructors allocate more memory than necessary and later trim the memory down to the proper amount (tested on smaller memory requirements to be able to observe that). This is a problem, since the brief moment when more RAM is allocated than necessary is crashing the program due to >4GB RAM usage.
Is there a way to prevent the program from dynamically allocating more than a given amount of RAM? If so, how can one set this property in a Visual Studio solution?
发布评论
评论(1)
事实证明,标准
vector
构造函数会短暂分配额外的内存来执行复制操作,如 所提到的彼得·科德斯(Peter Cordes)在评论中。这就是为什么这样做:可能会导致内存分配问题。
对我有用的解决方法是:
如果在编译之前已知所需的向量大小,则以下操作不会产生内存峰值:
如果向量大小需要保持动态,则 Mansoor 中的注释也不会产生内存峰值:
Turns out, the standard
vector
constructor is briefly allocating additional memory to perform a copy operation, as mentioned by Peter Cordes in a comment. That's why doing:may lead to memory allocation problems.
The workarounds that worked for me are:
If required vector size is known before compilation, the following does not produce a memory spike:
If the vector size needs to stay dynamical, the suggestion of Mansoor in the comments also does not produce a memory spike: