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?
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:
vector<vector<struct>> myVector(M, vector<struct>(N))
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:
vector<array<struct,N>> myVector(M)
If the vector size needs to stay dynamical, the suggestion of Mansoor in the comments also does not produce a memory spike:
vector<vector<struct>> myVector(M)
for(int i=0;i<M;i++){
myVector[i].reserve(N);
myVector[i].resize(N);
}